Advertisement
Guest User

Untitled

a guest
Mar 15th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7.  
  8. /*
  9.  * main method
  10.  *
  11.  * @args
  12. */
  13. main(int argc, char* argv[])
  14. {
  15.   int fd[2], pid, i;
  16.   char pipeBuffer[1024];
  17.  
  18.   //print error and exit program if no arguments were specified
  19.   if(argc != 2)
  20.   {
  21.     printf("Usage: my_program <filname of textfile>\n");
  22.     exit(0);
  23.   }
  24.  
  25.   //create a pipe
  26.   if(pipe(fd) == -1)
  27.   {
  28.     perror("pipe");
  29.     exit(EXIT_FAILURE);
  30.   }
  31.  
  32.   //create a fork
  33.   if((pid = fork()) == -1) //if fork failed
  34.   {
  35.     perror("fork");
  36.     exit(EXIT_FAILURE);
  37.   }
  38.  
  39.   if(pid == 0) //child created
  40.   {
  41.     close(fd[1]); //close unused write end
  42.  
  43.     int letterCounter = 0;
  44.     int counter = 0;
  45.     printf("\n");
  46.  
  47.     //read letters from the pipe
  48.     while(read(fd[0], pipeBuffer, 1) > 0)
  49.     {
  50.       if(isalpha(pipeBuffer[counter]))
  51.       {
  52.         letterCounter++;
  53.         printf("%c", pipeBuffer[counter]);
  54.       }
  55.  
  56.       counter++;
  57.     }
  58.  
  59.     printf("\n\nChild counting letters: %d\n\n", letterCounter);
  60.  
  61.  
  62.     close(fd[0]); //close finished read end
  63.     _exit(EXIT_SUCCESS);
  64.   }
  65.   else //parent
  66.   {
  67.     close(fd[0]); //close unused read end
  68.  
  69.     //store file contents in a buffer
  70.     char fileBuffer[1024];
  71.     FILE *fp = fopen(argv[1], "r");
  72.     int c;
  73.     int count = 0;
  74.  
  75.     while((c = fgetc(fp)) != EOF)
  76.     {
  77.       fileBuffer[count] = c;
  78.       printf("%d %c\n", count, fileBuffer[count]);
  79.       count++;
  80.     }
  81.     fclose(fp);
  82.  
  83.     printf("write return: %d\n", write(fd[1], fileBuffer, count)); //write to the pipe
  84.     write(fd[1], fileBuffer, count);
  85.  
  86.     close(fd[1]); //close finished write end
  87.     wait(NULL); //prevent zombies
  88.     exit(EXIT_SUCCESS);
  89.   }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement