实现功能:
主进程给子进程发送信号,子进程收到之后把信号量D打印出来。
#include <sys/wait.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
/**
* https://man7.org/linux/man-pages/man7/signal.7.html
* http://www.cs.kent.edu/~ruttan/sysprog/lectures/signals.html
*
*/
void handler(int sig, siginfo_t *info, void *ucontext) {
printf("signal handler %d \n", sig);
printf("info->si_signo %d \n", info->si_signo);
printf("info->si_code %d \n", info->si_code);
}
int main() {
pid_t cpid;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) {
struct sigaction act = { 0 };
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = &handler;
if (sigaction(SIGSEGV, &act, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
int i = 0;
while (1) {
sleep(1);
printf("child: %d \n", i++);
}
printf("child\n");
} else {
sleep(3);
kill(cpid, SIGSEGV);
sleep(3);
kill(cpid, SIGSEGV);
sleep(3);
kill(cpid, SIGSEGV);
// wait child process to exit
wait(NULL);
}
return EXIT_SUCCESS;
}