I have a code segment that looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t first, last;
last = fork();
if (last == 0) {
char *args[] = { "./last", NULL };
char *env[] = { NULL };
execve("./last", args, env);
_exit(1);
} else if (last == -1) {
fprintf(stderr, "Error: failed to fork last.\n");
exit(1);
}
first = fork();
if (first == -1) {
fprintf(stderr, "Error: failed to fork first.\n");
exit(1);
} else if (first > 0) {
int status;
waitpid(first, &status, 0);
} else {
char *args[] = { "./first", NULL };
char *env[] = { NULL };
execve("./first", args, env);
_exit(1);
}
return 0;
}
This works fine in a sense that I can see processes being invoked and running. However, my issue is that process last
has an infinity loop, and when process first
terminates, it still stays running. Is there a way in C to force process last
here to terminate also when process first
finishes?