home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / GianuzziV / SO1 / Efork.c < prev    next >
C/C++ Source or Header  |  2001-11-07  |  1KB  |  62 lines

  1. /* Efork.c 
  2.    Viene richiesto un comando Unix
  3.    Il comando e gli argomenti vengono inseriti in un array (args)
  4.    Il processo figlio esegue il comando con execvp  
  5. */
  6.  
  7. /* Nota: 
  8.    provare ad eseguire come comando "ls *.c"
  9.    Perche' viene dato un messaggio d'errore 
  10.    (del comando ls, non del programma Efork)?
  11. */
  12.  
  13. #include <stdio.h>
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16.  
  17. main()
  18. {
  19.      char buf[1024];
  20.      char *args[64];
  21.  
  22.      for (;;) 
  23.         {
  24.         printf("Comando > ");
  25.         if (gets(buf) == NULL) {
  26.              printf("\n");
  27.              return;
  28.              }
  29.         parse(buf, args);
  30.         execute(args);
  31.         } 
  32. }
  33.  
  34. /* la procedura parse individua gli argomenti */
  35. parse(char *buf, char **args)
  36. {
  37.      while (*buf != NULL) 
  38.         {
  39.         /* toglie blank e tab */ 
  40.         while ((*buf == ' ') || (*buf == '\t'))   *buf++ = NULL;
  41.         *args++ = buf;
  42.         while ((*buf != NULL) && (*buf != ' ') && (*buf != '\t')) buf++;
  43.      }
  44.      *args = NULL;
  45. }
  46.  
  47. /* esegue il comando dato */
  48. execute(char **args)
  49. {
  50.      int pid, status;
  51.  
  52.      if ((pid = fork()) < 0) {
  53.         perror("fork");
  54.         exit(1);             }
  55.  
  56.     if (pid == 0)   {
  57.         execvp(*args, args);
  58.         perror(*args);
  59.         exit(1);    }
  60.      wait(&status);
  61. }
  62.