C   126

shell.c

Guest on 4th September 2021 05:44:05 AM

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. int main(void) {
  7.   int PID;
  8.   char cmd[256];
  9.   while (1) {
  10.     printf("cmd: ");
  11.     scanf("%s",cmd);
  12.     if ( strcmp(cmd,"e")==0) /* loop terminates if type 'e'*/
  13.       exit(0);
  14.     /* creates a new process. Parent gets the process ID. Child gets 0 */
  15.     if ((PID=fork()) > 0)
  16.       wait(NULL);
  17.     else if (PID == 0) /* child process */
  18.       {
  19.         execlp (cmd,cmd,NULL);
  20.         /* exec cannot return. If so do the following */
  21.         fprintf (stderr, "Cannot execute %s\n", cmd);
  22.         exit(1); /* exec failed */
  23.       }
  24.     else if ( PID == -1)
  25.       {
  26.         fprintf (stderr, "Cannot create a new process\n");
  27.         exit (2);
  28.       }
  29.   }
  30.  
  31. }

Raw Paste


Login or Register to edit or fork this paste. It's free.