利用SIGUSR1和SIGUSR2實現父子程序同步輸出
阿新 • • 發佈:2018-12-31
#include<stdio.h> #include<signal.h> #include <unistd.h> void pdosig(int num ,struct __siginfo * _siginfo, void * ptr) { static int count = 0; printf("I am parent ,pid is %d,the proc : %d send signal: %d to me count is: %d\n",getpid(),_siginfo->si_pid,num,count); count+=2; sleep(1); kill(_siginfo->si_pid,SIGUSR2); } void cdosig(int num,struct __siginfo * _siginfo, void * ptr) { static int count = 1; printf("I am child ,pid is %d,the proc : %d send signal: %d to me count is: %d\n",getpid(),_siginfo->si_pid,num,count); count+=2; sleep(1); kill(_siginfo->si_pid,SIGUSR1); } int main() { struct sigaction sig; int pid = fork(); if(pid >0) { printf("i am father %d\n",getpid()); sig.sa_sigaction = pdosig; sigemptyset(&sig.sa_mask); sig.sa_flags=0; sigaction(SIGUSR1,&sig,NULL); } else { printf("i am child %d\n",getpid()); sig.sa_sigaction = cdosig; sigemptyset(&sig.sa_mask); sig.sa_flags=0; sigaction(SIGUSR2,&sig,NULL); kill(getppid(),SIGUSR1); } while(1) { sleep(1); } return 0; }
SIGUSR1和SIGUSR2是自定義訊號量,我們可以利用兩個訊號來實現父子程序同步輸出
int sigaction(int sig, const struct sigaction *restrict act, struct sigaction *restrict oact);函式來捕獲訊號,然後再利用KILL函式傳送訊號。從而實現同步。需要注意的是struct sigaction中的成員__sigaction_u是一個聯合體,此處我們需要用第二個即sa_sigaction才行,因為此回掉函式提供的引數中一個結構體struct __siginfo,此結構體如下
typedef struct __siginfo { int si_signo; /* signal number */ int si_errno; /* errno association */ int si_code; /* signal code */ pid_t si_pid; /* sending process */ uid_t si_uid; /* sender's ruid */ int si_status; /* exit value */ void *si_addr; /* faulting instruction */ union sigval si_value; /* signal value */ long si_band; /* band event for SIGPOLL */ unsigned long __pad[7]; /* Reserved for Future Use */ } siginfo_t;
其中pid_t包含傳送者的pid,因此我們可以根據傳送者的pid使父子程序建立聯絡,實現同步輸出