pipe_exec.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "sh.h"
  2. /*
  3. ** Launch multi-piping
  4. ** Free memory of fd, cmd_opt, p variables.
  5. ** Wait for infinite fork to display again promt
  6. */
  7. void launch_pipes(t_e *e, t_pipe *p, t_pipe_redir **t)
  8. {
  9. p->i = -1;
  10. while (++p->i <= p->nbr)
  11. {
  12. parse_exec(e, p, t);
  13. // parse_redirection(e, p, p->cmd_pipe[p->i]);
  14. if (p->i != 0)
  15. free(p->fd[p->i - 1]);
  16. }
  17. free(p->cmd_pipe);
  18. p->cmd_opt[p->i] = NULL;
  19. free(p->fd);
  20. free(p);
  21. p->i = -1;
  22. while (++p->i <= p->nbr)
  23. wait(NULL);
  24. }
  25. /*
  26. ** Split, trim and remove cotes before execution
  27. ** Launch pipes
  28. */
  29. void parse_exec(t_e *e, t_pipe *p, t_pipe_redir **t)
  30. {
  31. p->cmd_opt[p->i] = cmd_splitting(e, t[p->i]->itxt, ' ');
  32. ft_strdel(&p->cmd_pipe[p->i]);
  33. remove_cotes(p->cmd_opt[p->i]);
  34. handle_multi_piping(p);
  35. free(p->cmd_opt[p->i]);
  36. }
  37. /*
  38. ** Exit father if the command contain exit
  39. ** Fork for execve()
  40. ** Close current pipe output and redirect stdout into current pipe
  41. ** except for last cmd
  42. ** Close previous pipe input and redirect previous pipe into stdin
  43. ** except for first cmd
  44. ** Execute built-ins and executables which reads on stdin
  45. ** Exit current son fork
  46. ** Close previous pipe file descriptors except for first cmd to free fd
  47. */
  48. void handle_multi_piping(t_pipe *p)
  49. {
  50. int ok;
  51. ok = manage_cmd_1(p->cmd_opt[p->i]);
  52. if (fork() == 0)
  53. {
  54. if (p->i < p->nbr)
  55. {
  56. close(p->fd[p->i][0]);
  57. dup2(p->fd[p->i][1], STDOUT);
  58. }
  59. if (p->i > 0)
  60. {
  61. close(p->fd[p->i - 1][1]);
  62. dup2(p->fd[p->i - 1][0], STDIN);
  63. }
  64. if (ok == 0)
  65. manage_cmd_2(p->cmd_opt[p->i]);
  66. exit(0);
  67. }
  68. if (p->i > 0)
  69. {
  70. close(p->fd[p->i - 1][0]);
  71. close(p->fd[p->i - 1][1]);
  72. }
  73. }
  74. /*
  75. ** check every cmd, every cote type
  76. ** if block starts and ends with same cote:
  77. ** cut first and last char
  78. */
  79. void remove_cotes(char **cmd)
  80. {
  81. int i;
  82. int j;
  83. char *param;
  84. i = -1;
  85. param = "\'\"`";
  86. while (cmd[++i] != NULL)
  87. {
  88. j = -1;
  89. while (param[++j] != '\0')
  90. if (cmd[i][0] == param[j] && \
  91. cmd[i][ft_strlen(cmd[i]) - 1] == param[j])
  92. {
  93. cmd[i][ft_strlen(cmd[i]) - 1] = '\0';
  94. cmd[i] = &cmd[i][1];
  95. break ;
  96. }
  97. }
  98. }