Question: the code below is 90% finished, but there is one more part of implementation needed. the code below creates processes using fork, I want to
the code below is 90% finished, but there is one more part of implementation needed. the code below creates processes using fork,
I want to find 1.) the number of processes created. 2.) total number of files passed into the command line, 3.) number of files that exists and 4.) number of files that dosen't exists
Note that, no inter-process communication is required for child processes to send their count to the parent! They print their results individually, as shown above. However, by exiting with exit code 0 or 1, actually they respectively inform the parent if they were sucessful or not when opening file. The parent will know about these exit codes whet it waits for the child processes. So, after the for-loop in MAIN 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.
here is the code which takes in file names from cmd line, and counts the number of words in each file, you only have to find 1.) the number of processes created. 2.) total number of files passed into the command line, 3.) number of files that exists and 4.) number of files that dosen't exists
#include
int count_words(char *filename,int ppid); int main(int argc , char **argv) { //to store process id of the process int *pid_arr; 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); } } else { if(parent_pid == getpid()) //parent process wait(&status); } } 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; } }
So here is a sample output: Parent process created .... child processes to count words in ... files ... files have been counted sucessfully! ... files did not exist
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
