Question
Given the code below, find the 1.) the number of processes created. 2.) total number of files passed into the command line, 3.) number of
Given the code below, find the 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.
HINT: Use wait() to get exit status from each child.
#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);
// WHERE IMPLEMANTION SHOULD HAPPEN BASED ON THE INSTRUCTIONS ABOVE } } 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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started