realtime/ex03/t03_sig_child.c

49 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
void handle_sigint(int sig) {
// Father ignores SIGINT
printf("Father process received SIGINT, but ignoring it.\n");
}
void handle_son_termination(int status) {
if (WIFEXITED(status)) {
printf("Son terminated with exit status %d.\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Son terminated by signal %d.\n", WTERMSIG(status));
} else {
printf("Son terminated with unknown status.\n");
}
}
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Son process
signal(SIGINT, SIG_DFL); // Allow son process to be terminated by SIGINT
for (int i = 0; i < 10; ++i) {
printf("Son PID: %d\n", getpid());
sleep(1);
}
printf("Son terminating after 10 seconds.\n");
exit(0);
} else {
// Father process
signal(SIGINT, handle_sigint); // Ignore SIGINT in father
int status;
waitpid(pid, &status, 0); // Wait for son's termination
handle_son_termination(status);
}
return 0;
}