所以,这个问题很有意义。这是一个使用信号和信号处理程序的练习。
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是相反的(或者你需要它)。