程序間的通訊(六)
阿新 • • 發佈:2018-12-24
編寫程式完成下列要求:
程序A向程序B傳送訊號,該訊號的附帶資訊為一個字串“Hello world”;
程序B完成接收訊號的功能,並且打印出訊號名稱以及隨著訊號一起傳送過來的字串值。
和上一個實驗類似,傳送程序利用sigqueue函式能夠將更多的資訊傳送給接受程序。
程式如下:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void handler(int sig,siginfo_t* info,void *p) { printf("The str is: %s\n",info->si_value.sival_ptr); } int main() { int pid; struct sigaction act; act.sa_sigaction = handler; act.sa_flags = SA_SIGINFO; pid = fork(); if(pid < 0) perror("fork"); else if(pid == 0) { printf("This is the receive process!\n"); if(sigaction(SIGUSR1,&act,NULL) < 0) perror("sigaction"); while(1); } else { printf("This is the send process!\n"); union sigval mysigval; mysigval.sival_ptr = "hello world"; sleep(1); if(sigqueue(pid,SIGUSR1,mysigval) < 0) perror("sigqueue"); } return 0; }
程式執行結果: