exec.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "sh.h"
  2. /*
  3. ** Renew HOME and PATH environnement variables before.
  4. ** Handle ~
  5. ** Execute builtins.
  6. ** Else, new fork process to execute executables.
  7. */
  8. int manage_cmd_1(char **cmd)
  9. {
  10. g_home = get_tenv("HOME");
  11. cmd = change_tilde_to_home(cmd);
  12. g_path = ft_strsplit(get_tenv("PATH"), ':');
  13. if (ft_strcmp(cmd[0], "cd") == 0)
  14. cd(&cmd[1]);
  15. else if (ft_strcmp(cmd[0], "setenv") == 0 || \
  16. ft_strcmp(cmd[0], "export") == 0)
  17. ft_setenv(cmd[1]);
  18. else if (ft_strcmp(cmd[0], "unsetenv") == 0)
  19. ft_unsetenv(cmd[1]);
  20. else if (ft_strcmp(cmd[0], "exit") == 0)
  21. exit(0);
  22. else
  23. return (0);
  24. return (1);
  25. }
  26. void manage_cmd_2(char **cmd)
  27. {
  28. if (ft_strcmp(cmd[0], "env") == 0 && cmd[1] == NULL)
  29. ft_puttab(g_tenv);
  30. else if (ft_strcmp(cmd[0], "pwd") == 0)
  31. ft_putendl(get_pwd());
  32. else
  33. execute(cmd);
  34. }
  35. /*
  36. ** If local executable:
  37. ** Check file exist.
  38. ** Check user have executable rights on it.
  39. ** Execute it and exit fork.
  40. ** Else
  41. ** Execute direct given path like /bin/ls
  42. ** Search for executable in PATH paths.
  43. ** then run it.
  44. ** exit the fork if the no execution because execution stop the fork
  45. */
  46. void execute(char **cmd)
  47. {
  48. int i;
  49. char *path;
  50. if (cmd[0][0] == '.' && cmd[0][1] == '/' && cmd[0][2] != '\0')
  51. {
  52. cmd[0] = ft_strdup(&cmd[0][2]);
  53. if (access(cmd[0], F_OK) == -1)
  54. error_message(cmd[0], "no such executable", "exit");
  55. else if (access(cmd[0], X_OK) == -1)
  56. error_message(cmd[0], "no rights to execute it", "exit");
  57. else
  58. execve(cmd[0], &cmd[0], g_tenv);
  59. }
  60. else if (g_path != NULL)
  61. {
  62. i = -1;
  63. while (g_path[++i] != NULL)
  64. {
  65. path = ft_strjoin(g_path[i], ft_strjoin("/", cmd[0]));
  66. check_file_exist_exec_rights(path, cmd);
  67. check_file_exist_exec_rights(cmd[0], cmd);
  68. }
  69. }
  70. error_message(cmd[0], "no such command", "exit");
  71. }
  72. void check_file_exist_exec_rights(char *path, char **cmd)
  73. {
  74. if (access(path, F_OK) != -1)
  75. {
  76. if (access(path, X_OK) != -1)
  77. execve(path, &cmd[0], g_tenv);
  78. else
  79. error_message(path, "no rights to execute it", "exit");
  80. }
  81. }