Advertisement
heavenriver

shellpipe.c

Nov 30th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1.  /* simple shell, parses batches of commands separated by pipes and executes them in separate processes */
  2.  /* useful characters: [] # */
  3.  
  4.  # include <stdio.h>
  5.  # include <string.h>
  6.  # include <fcntl.h> // for O_RDONLY
  7.  # include <stdlib.h> // for exit()
  8.  # include <unistd.h> // for execlp()
  9.  
  10.  # define errormsg(x) { puts(x); exit(1); }
  11.  # define SIZE 1024
  12.  
  13.  int main(int argc, char * argv[])
  14.     {
  15.      char *cmd[SIZE]; // stores the current command
  16.      int index = 0; // read index
  17.      int quit = 0;
  18.      int processes = 0; // active processes
  19.      int status; // child or parent process
  20.      char c;
  21.      printf("Type command: ");
  22.      while(!quit && c != EOF)
  23.     {
  24.      index++;
  25.      c = getchar();
  26.      if(c != '\0' && c != '|')
  27.         cmd[index] = c;
  28.      if(c == '|') // executes command and empties buffer
  29.         {
  30.          int pid = fork();
  31.          processes++; // process added
  32.          if(pid != 0) wait(&status);
  33.          execlp(cmd, cmd, 0);
  34.          cmd = ""; // COMPILATION ERROR here
  35.         }
  36.      if(strcmp(cmd, "quit\n") == 0) quit = 1;
  37.     }
  38.      printf("Batch executed\n");
  39.      int i;
  40.      for(i = 0; i < processes; i++) // waits until all processes have terminated
  41.     wait(&status);
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement