pipe_parsing.c 2.2 KB

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