Linux高级编程基础——进程间通信之通过信号发送额外的字符串

进程间通信之通过信号发送额外的字符串

  1. 进程A向进程B发送信号,该信号的附带信息为一个字符串“Hello world”;
  2. 进程B完成接收信号的功能,并且打印出信号名称以及随着信号一起发送过来的字符串值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>

void sig_action(int signo, siginfo_t *info, void *addr) 
  {  
     if (signo == SIGUSR1)
      printf ("the signo is : SIGUSR1 \n");
     printf("%s\n", (char*)info->si_value.sival_ptr);       //打印随着信号一起传递过来的字符串
  }
 int main(int argc, char* const argv[]) 
{
   struct sigaction act;
   act.sa_sigaction = sig_action;   //定义接受信号的处理函数
   act.sa_flags = SA_SIGINFO;    //设置该参数表示可以接收额外的参数;
   sigaction(SIGUSR1, &act, NULL);    //这个是信号的接受函数
   pid_t pid;
   if ((pid = fork()) == -1) 
       printf ("fault fork \n");
   else if (pid == 0) 
    {
       union sigval val;
       val.sival_ptr = "hello world";   //把字符串发在 sigqueue函数的第三个参数中会在信号发送时整合到在sigqueue函数的第二个参数中,一起发送给接受信号的进程
       sigqueue(getppid(), SIGUSR1, val);    //这个是信号的发送函数
     }
   while (((pid = wait(NULL)) == -1 && errno == EINTR) || pid > 0)  {}

   return 0;
 }

/*

发送字符串只能在 共享内存或者 同一进程下 才可以发送

*/

猜你喜欢

转载自blog.csdn.net/qq_40663274/article/details/83926564