不使用 fork() 的两个进程之间的通信

Communication between two processes without using fork()

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

工作区:ubuntu19

语言:C.

任务是这样的:

我的问题是这样的:

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

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

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 是相反的(或者您需要它)。