mysh.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * File: mysh.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 31 octobre 2018, 12:43
  6. */
  7. #define _POSIX_C_SOURCE 2
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <fcntl.h>
  12. #include <sys/stat.h>
  13. #include <sys/types.h>
  14. #include <wait.h>
  15. #include <signal.h>
  16. #include "error.h"
  17. #include "str.h"
  18. #include "parser.h"
  19. #include "command.h"
  20. #include "execute.h"
  21. #include "mysh.h"
  22. /* --- Extern --- */
  23. extern Error error;
  24. extern boolean exitsh;
  25. /* --- Global --- */
  26. pid_list pidlist;
  27. pid_node* active = NULL;
  28. int job = 1;
  29. /* --- Fonctions privées --- */
  30. void test_write() {
  31. char* a = "azerty\n";
  32. int tmp = write(1, a, strlen(a));
  33. printf("%d\n", tmp);
  34. }
  35. void test_tmp_file(){
  36. int a;
  37. FILE* f = tmpfile();
  38. printf("F : %d\n", f == NULL);
  39. int fd = fileno(f);
  40. printf("%d : %ld\n", fd, write(fd, "bonjour", 8));
  41. a = lseek(fd, 0L, SEEK_SET);
  42. sleep(2);
  43. char buf[10];
  44. memset(buf, 0 , 10);
  45. a = read(fd, buf, 10);
  46. printf("%d : %s\n", a, buf);
  47. close(fd);
  48. }
  49. void test(){
  50. CommandTab ct;
  51. char str[BUFFER_SIZE];
  52. int a;
  53. //Initialisation structures
  54. error_finit("mysh.log");
  55. ini_pid_list(&pidlist);
  56. //Recup ligne
  57. //printf("%s\n", fgets(str, 500, stdin));&
  58. memset(str, 0, 500);
  59. a = read(STDIN, str, 500);
  60. printf("%s\n", str);
  61. //Separe les commandes
  62. a = parse_line(&ct, str);
  63. if(a == SHELL_ERR){
  64. addserror("Erreur lors du parse de la ligne");
  65. error.exit_err();
  66. }
  67. //Parse les commandes
  68. a = parse_all_command(&ct);
  69. if(a == SHELL_FAIL){
  70. addserror("Erreur lors du parse des commandes");
  71. error.exit_err();
  72. }
  73. //Affiche resultat
  74. for (int i = 0; i < ct.length; i++) {
  75. Command* c = ct.cmd[i];
  76. printf("Commande %d (%s) : \n", i, c->name);
  77. for (int j = 0; j < c->argc; j++) {
  78. printf(" Argument %d : %s\n", j, c->argv[j]);
  79. }
  80. printf("Commande en fond : %d\n\n", ct.bck);
  81. //Si c'est une commande interne on l'execute
  82. if(is_internal_cmd(ct.cmd[i]->name)){
  83. show_current_dir(NULL, "\n");
  84. printf("Result : %d\n", launch_internal_command(ct.cmd[i]));
  85. show_current_dir(NULL, "\n");
  86. }
  87. }
  88. //Nettoyage structures
  89. clean_command(&ct);
  90. clean_pid(&pidlist);
  91. error.exit();
  92. }
  93. /* --- Fonctions utilitaires --- */
  94. void show_current_dir(const char* before, const char* after) {
  95. char buffer[BUFFER_SIZE];
  96. if (getcwd(buffer, sizeof (buffer)) == NULL) {
  97. addperror("Erreur getcwd()");
  98. } else {
  99. if(before == NULL && after == NULL){
  100. printf("%s", buffer);
  101. } else if(before == NULL){
  102. printf("%s%s", buffer, after);
  103. } else if(after == NULL){
  104. printf("%s%s", before, buffer);
  105. } else {
  106. printf("%s%s%s", before, buffer, after);
  107. }
  108. }
  109. fflush(stdout);
  110. }
  111. int get_line(char* buffer){
  112. memset(buffer, 0, BUFFER_SIZE);
  113. if(read(STDIN, buffer, BUFFER_SIZE) == ERR){
  114. addperror("Impossible de lire dans STDIN");
  115. return SHELL_ERR;
  116. }
  117. return SHELL_OK;
  118. }
  119. int get_tmp_file(){
  120. FILE* f = tmpfile();
  121. if(f == NULL){
  122. adderror("Impossible de créer un fichier temporaire");
  123. return SHELL_ERR;
  124. }
  125. return fileno(f);
  126. }
  127. /* --- Main --- */
  128. int main(int argc, char* argv[]) {
  129. //Declaration variables
  130. CommandTab ct;
  131. int result;
  132. char line[BUFFER_SIZE], before[BUFFER_SIZE];
  133. sigset_t sigs_new, sigs_old, sigs_block;
  134. //Initialisation structures
  135. error_finit("mysh.log");
  136. ini_pid_list(&pidlist);
  137. //Preparation affichage
  138. sprintf(before, "\x1b[32m%s:\x1b[36m", getlogin());
  139. //Traitement des signeaux
  140. result = sigemptyset(&sigs_new);
  141. if(result == ERR){
  142. addperror("Impossible de récuperer un ensemble de signaux vide");
  143. error.print("Erreur pendant l'initialisation\n");
  144. clean_pid(&pidlist);
  145. error.exit_err();
  146. }
  147. //On bloque que sigchld
  148. result = sigaddset(&sigs_new, SIGCHLD);
  149. if(result == -1){
  150. addperror("Impossible d'ajouter SIGCHLD à l'ensemble de signaux");
  151. error.print("Erreur pendant l'initialisation\n");
  152. clean_pid(&pidlist);
  153. error.exit_err();
  154. }
  155. result = sigprocmask(SIG_BLOCK, &sigs_new, &sigs_old);
  156. if(result == -1){
  157. addperror("Impossible de bloquer les signaux de l'ensemble");
  158. error.print("Erreur pendant l'initialisation\n");
  159. clean_pid(&pidlist);
  160. error.exit_err();
  161. }
  162. //Boucle infini de lecture
  163. while(!exitsh){
  164. //On regarde si un fils en fond est mort
  165. if(sigpending(&sigs_block) == ERR){
  166. addperror("Impossible de recuperer les signaux en attentes");
  167. } else if(sigismember(&sigs_block, SIGCHLD)){
  168. job--;
  169. }
  170. //Affichage repertoire
  171. show_current_dir(before, ">\x1b[0m ");
  172. //Lecture ligne
  173. if(get_line(line) == SHELL_ERR){
  174. error.print("Impossible de lire les commandes\n");
  175. clean_pid(&pidlist);
  176. error.exit_err();
  177. }
  178. //Parse la ligne et commandes
  179. result = parse_line(&ct, line);
  180. if(result == SHELL_ERR){
  181. error.print("Impossible d'analyser la ligne\n");
  182. addserror("Erreur lors du parse de la ligne");
  183. continue;
  184. }
  185. //Si aucune commande on passe
  186. printf("Nb cmd : %d\n", ct.length);
  187. if(ct.length == 0){
  188. clean_command(&ct);
  189. continue;
  190. }
  191. //Parse les commandes
  192. result = parse_all_command(&ct);
  193. if(result == SHELL_FAIL){
  194. error.print("Impossible d'analyser la commande\n");
  195. addserror("Erreur lors du parse des commandes");
  196. continue;
  197. }
  198. //Execute
  199. result = run(ct, NULL);
  200. printf("Result : %d\n", result);
  201. //Vide le resultat du parse de la ligne de commande
  202. clean_command(&ct);
  203. }
  204. //Nettoyage
  205. clean_pid(&pidlist);
  206. error.end();
  207. return EXIT_SUCCESS;
  208. }
  209. int run(CommandTab ct, int* status){
  210. pid_t pid;
  211. int result = 0;
  212. //Si en fond creation d'un fork pour executer les commandes
  213. printf("bck : %d\n", ct.bck);
  214. if(ct.bck){
  215. pid = fork();
  216. if(pid == ERR){
  217. addperror("Erreur lors du fork pour l'execution des commandes");
  218. error.print("Erreur systeme, impossible de continuer\n");
  219. return SHELL_ERR;
  220. }
  221. //Fils
  222. if(pid == 0){
  223. int stat = 0;
  224. ct.bck = 0;
  225. result = run(ct, &stat);
  226. //Message de fin + retour
  227. if(result == SHELL_FAIL){
  228. printf("\n%s (jobs=[%d], pid=%d) terminée avec status=-1\n", ct.line, job, getpid());
  229. exit(EXIT_FAILURE);
  230. }
  231. printf("\n%s (jobs=[%d], pid=%d) terminée avec status=%d\n", ct.line, job, getpid(), stat);
  232. exit(EXIT_SUCCESS);
  233. }
  234. printf("[%d] %d\n", job, pid);
  235. //Ajout du fils dans la liste des pid
  236. add_pid(&pidlist, pid, job++);
  237. //Pour le pere c'est fini
  238. return SHELL_OK;
  239. }
  240. //Sinon execution de chaque commande
  241. Command* c;
  242. int tube[ct.length][2];
  243. int tubepos = 0;
  244. int infd = -1, outfd = -1, errfd = -1;
  245. boolean bpipe = false, skippipe = false, skip = false;
  246. //Parcours les commandes
  247. for(int i = 0; i < ct.length; i++){
  248. c = ct.cmd[i];
  249. //Si on skip
  250. if(skip){
  251. skip = false;
  252. continue;
  253. }
  254. //Si pipe avant
  255. if(skippipe){
  256. //Si fin chaine pipe
  257. if(c->next != SHELL_PIPE){
  258. skippipe = false;
  259. }
  260. //Passe la commande
  261. continue;
  262. }
  263. //Si pipe creation d'un fichier commun
  264. skippipe = c->next == SHELL_PIPE ;
  265. if(c->next == SHELL_PIPE && c->output == STDOUT){
  266. skippipe = false;
  267. bpipe = true;
  268. //Creation tube
  269. if(pipe(tube[tubepos]) == ERR){
  270. addperror("Impossible de créer un tube");
  271. return SHELL_FAIL;
  272. }
  273. //Redirection
  274. c->output = tube[tubepos][TUBE_ECRITURE];
  275. if(ct.cmd[i + 1]->input == STDIN){
  276. ct.cmd[i + 1]->input = tube[tubepos][TUBE_LECTURE];
  277. }
  278. }
  279. //Effectue les redirections IO
  280. if(c->input != STDIN){
  281. infd = redirect_fd2(STDIN, c->input);
  282. if(infd == ERR){
  283. return SHELL_FAIL;
  284. }
  285. }
  286. if(c->output != STDOUT){
  287. outfd = redirect_fd2(STDOUT, c->output);
  288. if(outfd == ERR){
  289. return SHELL_FAIL;
  290. }
  291. }
  292. if(c->error != STDERR){
  293. errfd = redirect_fd2(STDERR, c->error);
  294. if(errfd == ERR){
  295. return SHELL_FAIL;
  296. }
  297. }
  298. //Execute la commande
  299. if(is_internal_cmd(c->name)){
  300. result = launch_internal_command(c);
  301. } else if(is_executable_file(c->name)){
  302. result = exec_file(c->name, c->argv);
  303. } else {
  304. result = exec_shell(c->name, c->argv);
  305. }
  306. //Si on a une variable pour stocker le status de retoure
  307. if(status != NULL){
  308. *status = result;
  309. }
  310. //Reset IO
  311. if(c->input != STDIN){
  312. infd = redirect_fd(STDIN, infd);
  313. if(infd == ERR){
  314. return SHELL_FAIL;
  315. }
  316. }
  317. if(c->output != STDOUT){
  318. outfd = redirect_fd(STDOUT, outfd);
  319. if(outfd == ERR){
  320. return SHELL_FAIL;
  321. }
  322. }
  323. if(c->error != STDERR){
  324. errfd = redirect_fd(STDERR, errfd);
  325. if(errfd == ERR){
  326. return SHELL_FAIL;
  327. }
  328. }
  329. //Fermeture tube
  330. if(bpipe){
  331. bpipe = false;
  332. if(close(outfd) == ERR){
  333. addperror("Impossible de fermer tube ecriture");
  334. return SHELL_FAIL;
  335. }
  336. if(close(c->output) == ERR){
  337. addperror("Impossible de fermer tube ecriture");
  338. return SHELL_FAIL;
  339. }
  340. c->output = STDOUT;
  341. }
  342. //Agit en fonction de la jointure avec la prochaine commande
  343. if(c->next == SHELL_IF){
  344. if(result != EXIT_SUCCESS){
  345. skip = true;
  346. }
  347. } else if(c->next == SHELL_ELSE){
  348. if(result == EXIT_SUCCESS){
  349. skip = true;
  350. }
  351. }
  352. }
  353. if(result != EXIT_SUCCESS){
  354. return SHELL_FAIL;
  355. }
  356. return SHELL_OK;
  357. }