通过信号完成父子进程间的通信
通过信号完成父子进程间的通信
// 通过信号父子进程发送数据 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void sig_parent(int code, siginfo_t * info, void *arg) { // 捕捉SIGUSER2 printf("parent pid : %d, output data : %d,\n", getpid(), info->si_int); union sigval val; val.sival_int = ++(info->si_int); sigqueue(getpid() + 1, SIGUSR1, val); } void sig_child(int code, siginfo_t * info, void *arg) { // 捕捉SIGUSER1 printf("child pid : %d, output data : %d,\n", getpid(), info->si_int); union sigval val; val.sival_int = ++(info->si_int); sigqueue(getpid() - 1, SIGUSR2, val); } int main() { // 屏蔽信号 sigset_t set, oset; sigemptyset(&set); sigaddset(&set, SIGUSR1); sigprocmask(SIG_SETMASK, &set, &oset); // 1. 创建父子进程 pid_t pid = fork(); if (pid > 0) { // 捕捉 struct sigaction act, oact; act.sa_sigaction = sig_parent; act.sa_flags = SA_SIGINFO; sigemptyset(&act.sa_mask); sigaction(SIGUSR2, &act, &oact); // 发送信号 union sigval val; val.sival_int = 1; sigqueue(pid, SIGUSR1, val); while (1) sleep(1); } else if (pid == 0) { struct sigaction act, oact; act.sa_sigaction = sig_child; act.sa_flags = SA_SIGINFO; sigemptyset(&act.sa_mask); sigaction(SIGUSR1, &act, &oact); // 解除屏蔽 sigset_t set; sigemptyset(&set); sigprocmask(SIG_SETMASK, &set, NULL); while (1) sleep(1); } else { perror("fork call failed.\n"); exit(0); } return 0; }

浙公网安备 33010602011771号