pipe_parsing.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "sh.h"
  2. /*
  3. ** Check no || are present to prevent segfault
  4. ** Count number of pipes
  5. ** Malloc pipe file descriptors
  6. ** Create pipes
  7. ** Split at pipes
  8. */
  9. void pipe_init(t_e *e, char *all_cmd)
  10. {
  11. t_pipe *p;
  12. int i;
  13. t_pipe_redir **t;
  14. p = (t_pipe*)malloc(sizeof(t_pipe));
  15. if (ft_strstr(all_cmd, "||") != NULL)
  16. {
  17. error_message("", "I do not handle \"||\"", NULL);
  18. return ;
  19. }
  20. p->nbr = count_pipe_nbr(e, all_cmd);
  21. p->fd = (int**)malloc(sizeof(int*) * p->nbr);
  22. i = -1;
  23. while (++i < p->nbr)
  24. {
  25. p->fd[i] = (int*)malloc(sizeof(int) * 2);
  26. if (pipe(p->fd[i]) == -1)
  27. {
  28. error_message("pipe", "creation issue", NULL);
  29. return ;
  30. }
  31. }
  32. p->cmd_pipe = cmd_splitting(e, all_cmd, '|');
  33. t = (t_pipe_redir**)malloc(sizeof(t_pipe_redir*) * (p->nbr + 2));
  34. fill_pipe_redir_data(e, p, t);
  35. // display_data(t);
  36. // ft_strdel(&all_cmd); // segfault pour "b ; b"
  37. pipe_parsing(p, e, t);
  38. }
  39. void display_data(t_pipe_redir **t)
  40. {
  41. int i;
  42. i = -1;
  43. while (t[++i] != NULL)
  44. ft_printf("itxt: '%s'\nifd: %d\noperator: '%s'\nofd: %d\notxt: '%s'\n\n", \
  45. t[i]->itxt, t[i]->ifd, t[i]->operator, t[i]->ofd, t[i]->otxt);
  46. }
  47. /*
  48. ** Malloc for commands and their options
  49. ** For all command remove non visible char before and after cmd
  50. ** Check a command is present
  51. ** If cmd == "": return
  52. ** If no cmd between pipe: display error message and return
  53. ** Split cmd and his options
  54. ** Free cmd_pipe
  55. */
  56. void pipe_parsing(t_pipe *p, t_e *e, t_pipe_redir **t)
  57. {
  58. int val;
  59. int i;
  60. p->cmd_opt = (char***)malloc(sizeof(char**) * (p->nbr + 1));
  61. i = -1;
  62. while (p->cmd_pipe[++i] != NULL)
  63. {
  64. val = -1;
  65. p->cmd_pipe[i] = ft_strtrim(p->cmd_pipe[i]);
  66. if ((val = check_cmd_presence(p->cmd_pipe[i])) != 1)
  67. {
  68. if (val == 0)
  69. error_message("", "no cmd between pipes or semicolons", NULL);
  70. return ;
  71. }
  72. }
  73. launch_pipes(e, p, t);
  74. }
  75. /*
  76. ** Count number of pipe occurences on comma splitted string.
  77. ** Only pipe betweeen non-coted blocks are counted.
  78. */
  79. int count_pipe_nbr(t_e *e, char *str)
  80. {
  81. int i;
  82. int occ;
  83. occ = 0;
  84. i = -1;
  85. while (str[++i] != '\0')
  86. {
  87. if (str[i] == '|' && is_on_coted_block(e, e->slen + i) == 1)
  88. occ++;
  89. else if ((str[i] == '>' || str[i] == '<') && \
  90. is_on_coted_block(e, e->slen + i) == 1)
  91. {
  92. occ++;
  93. i++;
  94. }
  95. }
  96. return (occ);
  97. }