首页 > 解决方案 > 不使用 fork() 的两个进程之间的通信

问题描述

我正在尝试进行乒乓球练习,我寻求指导/方向,但不是解决方案,因此我可以学习。

工作区:ubuntu 19

语言:C。

任务是这样的:

我的问题是这样的:

  1. 如何将 pid 作为命令行参数传递?
  2. 如何在第二个进程中读取 PID?

标签: clinuxvisual-studio-codesignalsubuntu-19.10

解决方案


所以,这个问题很有意义。这是一个使用信号和信号处理程序的练习。

Pong.c 会有类似的东西(但你应该自己添加错误处理,例如,没有 pid):

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

void sigHandler( int signo, siginfo_t *siginfop, void *context)
{
   /* send another signal back to ping, you dont need the pid you read from cmd line */ 
   union sigval sv;
   if( siginfop != NULL )
       sigqueue( siginfop->si_pid, SIGUSR1, sv)
 }
      
void main( int argc, const char *argv[] )
{
   int ping_pid = atoi(argv[1]);
   
   /* this is for receiving signals */
   struct sigaction sa;
   sa.sigaction = sigHandler;
   sigemptyset(&sa.sa_mask);
   sa.sa_flags = SA_NODEFER | SA_SIGINFO;
   
   /* you send SIGUSR1 from pong; you'll receive SIGUSR2 from ping */
   if( sigaction(SIGUSR2, &sa, NULL) == -1) perror("sigaction");
   

  /* this is for sending the first signal */
   union sigval sv;
   
   if( sigqueue( ping_pid, SIGUSR1, sv) == -1 ) perror("sigqueue")
   /*
    do something
    while u wait
   */
  }

而对于另一个程序,在 ping.c 中你也这样做,除了你没有从命令行读取 pid,你只需等待其他进程的信号;并且信号ID是相反的(或者你需要它)。


推荐阅读