heredoc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #include "sh.h"
  2. /*
  3. ** Launch heredoc: double left redirection <<
  4. ** Unset term caps modes
  5. ** retrieve text through a prompt
  6. ** Set term caps modes
  7. ** backup STDIN, pipe the text in STDIN
  8. ** wait the fork, launch the cmd with the upper text
  9. ** restore STDIN
  10. */
  11. void prompt_redirection(t_e *e, t_pipe *p, t_pipe_redir *t)
  12. {
  13. char *txt;
  14. int pipefd[2];
  15. int stdfd;
  16. int i;
  17. set_term_modes(0);
  18. txt = prompt_heredoc(e, txt, t->otxt, i);
  19. set_term_modes(1);
  20. pipe(pipefd);
  21. if (fork() == 0)
  22. {
  23. close(pipefd[0]);
  24. ft_putstr_fd(txt, pipefd[1]);
  25. ft_strdel(&txt);
  26. exit(0);
  27. }
  28. close(pipefd[1]);
  29. stdfd = dup(0);
  30. dup2(pipefd[0], 0);
  31. wait(NULL);
  32. if (fork() == 0)
  33. {
  34. manage_cmd_2(e, cmd_splitting(e, t->itxt, ' '));
  35. exit(0);
  36. }
  37. wait(NULL);
  38. close(pipefd[0]);
  39. close(0);
  40. dup(stdfd);
  41. }
  42. /*
  43. ** prompt to enter text, get entered lines
  44. ** join them till it encounter the end of file string except first time
  45. ** read, join the buffer till it encounter ENTER
  46. ** if ctrl + d: print '\n'; return txt
  47. ** return the text
  48. */
  49. char *prompt_heredoc(t_e *e, char *txt, char *eof, int i)
  50. {
  51. t_e *h;
  52. i = 0;
  53. h = (t_e*)malloc(sizeof(t_e));
  54. h->cmd = ft_strnew(0);
  55. while (ft_strcmp(h->cmd, eof) != 0)
  56. {
  57. if (i == 0)
  58. txt = ft_strnew(0);
  59. else
  60. {
  61. txt = ft_strjoinf(txt, ft_strjoinf(h->cmd, "\n", 1), 3);
  62. h->cmd = ft_strnew(0);
  63. }
  64. ft_putchar('>');
  65. if (here_edition(h, 1) == 1)
  66. {
  67. ft_putchar('\n');
  68. return (ft_strjoinf(txt, ft_strjoinf(h->cmd, "\n", 1), 3));
  69. }
  70. i++;
  71. }
  72. ft_strdel(&h->cmd);
  73. free(h);
  74. return (txt);
  75. }
  76. /*
  77. ** break loop if encounter ENTER
  78. ** if heredoc: print '\n'
  79. ** join the buffer
  80. ** if ctrl + d: end of file
  81. ** handle keys moving
  82. */
  83. int here_edition(t_e *h, int heredoc)
  84. {
  85. int ret;
  86. h->key = ft_strnew(4);
  87. while ((ret = read(0, h->key, 1)) > 0)
  88. {
  89. if (h->key[0] == 10)
  90. {
  91. if (heredoc == 1)
  92. ft_putchar('\n');
  93. break ;
  94. }
  95. if (ft_isprint(h->key[0]) == 1)
  96. {
  97. ft_putchar(h->key[0]);
  98. h->key[ret] = '\0';
  99. insert(h);
  100. }
  101. if (h->key[0] == 4)
  102. return (1);
  103. else
  104. handle_keys(h, 0);
  105. }
  106. return (0);
  107. }