Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<fcntl.h>
- typedef struct{
- int index;
- int num;
- }proc;
- /*
- The process parent receives N files from the user input. For each file it creates
- 1 processes child. Each process child reads its file and count the number of
- characters. The first process sends the number to the second process, which reads
- the number, compares it the its own counter and send forward to the third process
- the greater between the two. The last process send the number to the process parent
- who read the pipe and prints the number in the standard output.
- */
- void main(int argc, char **argv){
- proc myProc;
- int N=argc-1; // represents the number of argument (files)
- int i,j; // indexes
- proc msg; // the message received by parent
- int fd; // file descriptor
- int pid; // the process id returned by fork()
- char ch; // the buffer for file read
- int counter=0; // used to count the number of characters
- // declare and populate the N pipes (one for each child)
- int mypipe[N][2];
- for (j=0;j<N;j++)
- pipe(mypipe[j]); // populate with values
- // Create the N children
- for(i = 0; i < N; i++){
- pid=fork();
- if (pid < 0){
- printf("ERROR");
- }
- else if(pid == 0){
- // loop on pipes, close the ones not in use
- for (j=0;j<N;j++){
- if (i!=j) close(mypipe[j][1]);
- if(j!=i-1)close(mypipe[j][0]);
- }
- // Open file
- fd = open(argv[i+1], O_RDONLY);
- // Check if it was succefully opened
- if (fd < 0){
- printf("Error opeing the file %s \n", argv[i+1]);
- exit(1);
- }
- // Loop on file and read char by char
- while(read(fd, &ch, 1)>0){
- counter++;
- }
- //update struct info
- myProc.num = counter;
- myProc.index = i;
- // Close file after use
- close(fd);
- // If the porcess is not the first one
- if (i>0){
- // reading from previous
- read(mypipe[i-1][0], &msg, sizeof(proc));
- if (msg.num > myProc.num) {myProc.num=msg.num;myProc.index=msg.index;}
- }
- // Write on pipe the number of characters
- write(mypipe[i][1],&myProc,sizeof(proc));
- // Exit
- exit(0);
- }
- }
- // loop on pipes and close the ones not in use
- for (j=0;j<N;j++){
- close(mypipe[j][1]);
- if (j!=N-1) close(mypipe[j][0]);
- }
- read(mypipe[N-1][0],&msg,sizeof(proc));
- printf("MSG = %d with count %d \n", msg.index+1,msg.num);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement