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

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值