redirect.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "sh.h"
  2. /*
  3. ** if <: open file and dup it in STDIN, save stdfd
  4. ** elif <<: run bottow function
  5. ** elif > or >>: launch right_redirections()
  6. ** if > or >>: dup STDERR or STDOUT in to STDIN
  7. */
  8. void open_left_redirections(t_e *e, t_pipe *p, t_pipe_redir *t)
  9. {
  10. if (t->operator[0] == '|')
  11. return ;
  12. if (ft_strcmp(t->operator, "<") == 0)
  13. {
  14. p->fd[p->i][0] = open(t->otxt, O_RDONLY);
  15. p->fd[p->i][1] = dup(0);
  16. close(0);
  17. dup(p->fd[p->i][0]);
  18. }
  19. else if (ft_strcmp(t->operator, "<<") == 0)
  20. prompt_redirection(e, p, t);
  21. }
  22. /*
  23. ** for file writting: open, append or trunc
  24. ** for fd redirecting: ofd: output fd: dup ofd
  25. ** for '>&-': open '/dev/null'
  26. ** save stdfd, dup new fd in STDIN
  27. */
  28. void open_right_redirections(t_e *e, t_pipe *p, t_pipe_redir *t)
  29. {
  30. int fd_file;
  31. if (t->ofd == -100)
  32. {
  33. if (ft_strstr(t->operator, ">>") != NULL)
  34. fd_file = open(t->otxt, O_APPEND | O_WRONLY | O_CREAT, 0644);
  35. else
  36. fd_file = open(t->otxt, O_TRUNC | O_WRONLY | O_CREAT, 0644);
  37. t->ifd == 2 ? dup2(fd_file, STDERR) : dup2(fd_file, STDOUT);
  38. }
  39. else
  40. {
  41. if (t->otxt == NULL)
  42. close(t->ofd);
  43. else
  44. dup2(t->ifd, t->ofd);
  45. }
  46. }
  47. /*
  48. ** if != <<: close fd, restore stdfd
  49. */
  50. void close_redirections(t_e *e, t_pipe *p, t_pipe_redir *t)
  51. {
  52. if (ft_strcmp(t->operator, "<<") != 0 && t->operator[0] != '|')
  53. {
  54. close(p->fd[p->i][0]);
  55. if (ft_strcmp(t->operator, "<") != 0)
  56. t->ifd == '2' ? close(STDERR) : close(STDOUT);
  57. else
  58. close(0);
  59. dup(p->fd[p->i][1]);
  60. }
  61. }