Question: given the c code below, find the child number of process created, find number of files successfully opened and number of files successfully closed. CODE:

given the c code below, find the child number of process created, find number of files successfully opened and number of files successfully closed.

CODE:

#include #include #include

int count_words(char *filename,int ppid); int main(int argc , char **argv) { //to store process id of the process int i,count,pid,parent_pid,status; if(argc < 2) { printf("Usage: ./exename file1 file2 etc.. "); return -1; } //create the proces equal to argc-1 pid =(int*)malloc((argc-1)*sizeof(int)); count = argc; parent_pid=getpid(); for(i = 1; i < count; i++) { pid = fork(); if(pid == 0) { int words = count_words(argv[i],parent_pid); if(words > 0) printf("Child process for %s :number of words is %d ",argv[i],words); } }

for(i = 1; i < count; i++) {

// IMPLEMENT HERE, USE WAIT() HERE, MORE HINTS AT THE BOTTOM.

} return 0; } int count_words(char *filename,int ppid) { FILE *fp; int count=0; char str[20]; //execute this function only if child process of parent, no gradchild is allowed to execute this function! if(ppid == getppid()) { fp = fopen(filename,"r"); if(fp == NULL) { printf("Not able to open %s ",filename); return -1; } while(fscanf(fp,"%s",str)!=EOF) count++;

return count; } else return -1; }

SAMPLE OUTPUT OF PART YOU SHOULD IMPLEMENT Paren process created .... child processes to count words in ... files ... files have been counted sucessfully! ... files did not exist

HINT: So, after the above for-loop in the parent process, let parent have another loop to WAIT and GET EXIT code for each child using wait() system call. By INSPECTING the exit code for each child, parent can count how many child process were succesful and accordingly it counts that. When all child processes are waited, the parent prints that count to show how many files are counted successfully and how many files did not exist.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!