利用SIGUSR1和SIGUSR2实现父子进程同步输出

#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使父子进程建立联系,实现同步输出

猜你喜欢

转载自blog.csdn.net/woshichaoren1/article/details/85010572