Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //need two element int array for pipe
- int pd[2];
- //make pipe before child processes are made so every child writes to this one pipe
- if(pipe(pd) == -1)
- 44 {
- 45 error_exit("pipe");
- 46 }
- //NOTE: each pid = fork() is a new child process, so if in a loop
- //you will have n child process that the parent should wait on before
- //reading from the pipe, null reads make the program hang up
- if((pid = fork()) == 0)
- 63 {
- 64 fp = fopen(cp, "r");
- 65
- 66 if(fp == NULL)
- 67 {
- 68 fprintf(stderr, "%s: unable to read %s\n", pgname, cp);
- 69 exit(1);
- 70 }
- 71
- 72 // print current file (argv[i]) just for sanity, remove after testing
- 73 printf("%s\n", argv[i]);
- 74 printf("pid = %d\n", pid);
- 75
- 76 count(fp);
- 77
- 78 //write to pipe
- 79 //order is line, word, byte, filename, child pid!
- 80
- //note pd[1] is passed to write, this is always what you pass
- 81 if(write(pd[1], &words, MSGSIZE) == -1)
- 82 {
- 83 error_exit("write words failed");
- 84 }
- 85 if(write(pd[1], &lines, MSGSIZE) == -1)
- 86 {
- 87 error_exit("write lines failed");
- 88 }
- 89 if(write(pd[1], &bytes, MSGSIZE) == -1)
- 90 {
- 91 error_exit("write bytes failed");
- 92 }
- 93 return; //return from child statement
- 94 }
- //wait for all child process to end before continuing
- 98 while((wpid = wait(NULL)) > 0);
- //parent can read pipe now
- 101
- 102 int temp = 0;
- 103 char fname[MSGSIZE];
- //numberOfWritesToPipe needs to match number of times a child process wrote to the pipe
- //for example, wrote lines, writes, bytes, and file name from child process, so read pipe 4 times
- int numberOfWritesToPipe = 4;
- 104 for(i = 0; i < numberOfWritesToPipe; i++)
- 105 {
- 106 if(i < 3)
- 107 {
- //notice pd[0] passed to write, this is always the case
- 108 if((read(pd[0], &temp, sizeof(temp))) == -1)
- 109 {
- 110 error_exit("read failed (digit)");
- 111 }
- 112 switch(i)
- 113 {
- 114 case 0:
- 115 bytes += temp;
- 116 break;
- 117 case 1:
- 118 words += temp;
- 119 break;
- 120 case 2:
- 121 lines += temp;
- 122 break;
- 123 }
- 124 }
- 125 else
- 126 {
- 127 if((read(pd[0], buf, MSGSIZE)) == -1)
- 128 {
- 129 error_exit("read failed (string)");
- 130 }
- 131 printf("file name?? %s\n", buf);//figure out why this is failing
- 132 }
- 133 }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement