I have now compile it one by one. I also facing a problem about terminating the processes.
int main(int argc, char *argv[]) {
int n = 1;
int f = 1;
signal(SIG_ERR, sig_hand1);
signal(SIGINT, sig_hand1);
for (f; f < argc; f ){ \\create n-numberd fork.
nfork(f, argv);
}
for (n; n<argc; n ){ \\terminate the child one by one.
Rturn(n, argv);
}
return 0;
}
With the Rturn function
void Rturn(int n, char *argv[]){
int status;
struct rusage usage;
struct timeval start;
struct timeval end;
wait4(-1, &status, 0, &usage);
if(WIFSIGNALED(status)==1){
char *str = strdup(signame[WTERMSIG(status)]);
printf("\nThe command %c%s%c is interrupted by the %s\n\n", '"', argv[n], '"',str);
}
else if(WEXITSTATUS(status) == 255)
printf("The program experienced an error in starting the command: %s\n\n", argv[n]);
else
printf("\nThe command %c%s%c terminated with returned status code = %d\n\n", '"', argv[n], '"', WEXITSTATUS(status));
}
And nfork
void nfork(int n, char *argv[]){
if(fork() == 0){
printf("Process with id:%d created for the command: %s\n", getpid(), argv[n]);
fflush(stdout);
if(execlp(argv[n], argv[n], NULL) == -1){
printf("\nexeclp: %s\n\n", strerror(errno));
exit(-1);
}
}
}
I found that the message is not returned by the process but by the n in the loop.
For example, if I run
./test cd fake //with command cd and "fake"
Then it will return
monitor experienced an error in starting the command: cd
The expected return should be like this
monitor experienced an error in starting the command: fake
How can I locate the correct child to the variable n?
CodePudding user response:
On success, the fork()
function returns twice. In the parent process, its return value is the process ID of the new child. In the child process, the return value is 0. It is by the process ID returned to it that the parent can recognize specific children so as to wait for them, send signals to them, etc..
Your nfork()
function presently ignores the return value of fork()
except to check whether it is zero. This is wrong for two reasons:
The parent does not distinguish between success and failure of the
fork()
call. It just assumes that it succeeds.The parent wants to be able to later associate specific children with the corresponding value of n. Individual processes are identified by their process IDs. Only in
nfork()
is there an opportunity to associate child process IDs with n values, but the function fails to take advantage of it.
There are any number of ways that the association between child indices and child process IDs could be recorded, but the simplest would probably be to create an array to store them in. nfork()
would need to fill the array, and RTurn()
would need to draw from it the PID to wait for, which it would then supply to wait4()
as its first argument.