信号不仅可以用来处理异步事件,也可以用来传递数据。

利用函数sigaction跟sigqueue来实现进程间的数据传递。

 

程序1:发送数据

#include <stdio.h>
#include <sys/types.h>
#include <signal.h>




int main(int argc, char* argv[])
{
    union sigval send_val;
    send_val.sival_int = 1;
    
    //get the pid
    pid_t pid = atoi(argv[1]);
    //利用sigqueue给pid发送信号SIGINT,并携带数据value
    sigqueue(pid, SIGINT, send_val);


    return 0;
}

 

 

 

程序2:接收数据

 

#include <stdio.h>
#include <sys/types.h>
#include <signal.h>

//3参数的信号处理函数
void hand_singno(int signo, siginfo_t *siginfo, void *pvoid)
{
    printf("recv SIGINT,the data is:%d\n", siginfo->si_int);
}


int main(int argc, char* argv[])
{

    struct sigaction act;
    act.sa_sigaction = hand_singno;
    act.sa_flags = SA_SIGINFO;//指定使用3参数的信号处理函数
    
    //安装信号处理函数
    sigaction(SIGINT, &act, NULL);


    while(1);

    return 0;
}

 

整型数据从进程1传递给了进程2

posted on 2017-04-12 15:12  邶风  阅读(290)  评论(0编辑  收藏  举报