c - 不使用 fork() 的两个进程之间的通信
问题描述
我正在尝试进行乒乓球练习,我寻求指导/方向,但不是解决方案,因此我可以学习。
工作区:ubuntu 19
语言:C。
任务是这样的:
- 不要使用 () 叉子
- ping 进程正在等待信号
- Pong 进程从命令行获取 Ping PID 作为参数
- Pong 应该发送 SIGUSER1 信号到 ping
- Ping 将信号 SIGUSER2 返回到 pong 等等......
- 从 gdb 运行 2 个进程。
我的问题是这样的:
- 如何将 pid 作为命令行参数传递?
- 如何在第二个进程中读取 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是相反的(或者你需要它)。
推荐阅读
- python - Python点击选项 - 如果参数multiple没有传递,避免多次使用相同的选项
- android - 矩形中的 Android 屏幕边界
- php - Laravel > 5.5 会话和 API
- bash - 如何检查命令的输出是否包含字符串,如果字符串存在则运行命令
- ffmpeg - ffmpeg mp4 到 hls 限制输出块大小而不是持续时间
- c# - 选择 DropDownList1 值时,DropDownList2 中的重复值存储
- php - 如何在 PHP 中使用 mysql 表中的变量
- javascript - PHP中带有提交按钮的未定义索引
- python - 如何从元组中排除字符串以仅显示整数值?
- metal - 颜色的金属 Alpha 值不变