main.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "sh.h"
  2. /*
  3. ** Handle -c command
  4. */
  5. int main(int ac, char **av, char **env)
  6. {
  7. g_tenv = env;
  8. signal(SIGINT, sighandler);
  9. if (ac > 1)
  10. {
  11. if (ft_strcmp(av[1], "-c") == 0 && ac == 3 && ft_strlen(av[2]) > 0)
  12. comma_split(av[2]);
  13. if (ac == 2 && ft_strcmp(av[1], "-c") != 0)
  14. shell_script(av[1]);
  15. else
  16. ft_putendl("./21sh -c <command>\n./21sh <shell_script>");
  17. return (0);
  18. }
  19. open_shell();
  20. return (0);
  21. }
  22. /*
  23. ** Run shell script
  24. ** Read lines of the file
  25. ** Run the line
  26. */
  27. void shell_script(char *script_name)
  28. {
  29. int fd;
  30. char *line;
  31. fd = open(script_name, O_RDONLY);
  32. while (get_next_line(fd, &line) != 0)
  33. comma_split(line);
  34. }
  35. /*
  36. ** Display prompt.
  37. ** Read on standard stream.
  38. */
  39. void open_shell(void)
  40. {
  41. char *line;
  42. while (1)
  43. {
  44. line = NULL;
  45. while (line == NULL || line[0] == '\0')
  46. {
  47. ft_putstr(PROMPT);
  48. get_next_line(0, &line);
  49. comma_split(line);
  50. }
  51. }
  52. }
  53. /*
  54. ** Split at commas ';'.
  55. */
  56. void comma_split(char *line)
  57. {
  58. char **cmds;
  59. int i;
  60. i = -1;
  61. if ((cmds = ft_strsplit(line, ';')) != NULL)
  62. while (cmds[++i] != NULL)
  63. launch_pipe(cmds[i]);
  64. }
  65. /*
  66. ** Split command and his options at spaces and tabulations.
  67. ** Check if command contain printable characters to prevent segfault.
  68. */
  69. void split_cmd_and_his_options(char *cmd)
  70. {
  71. char **cmd_opts;
  72. cmd_opts = cmd_split(cmd, ' ', '\t');
  73. if (check_cmd_presence(cmd) == 1)
  74. manage_cmd(cmd_opts);
  75. }