c - 将值传递给子进程处理程序
问题描述
假设我通过 fork 从父进程创建子进程,并使用管道将 X 值传递给子进程。起初,子进程处于暂停状态,我使用 SIGINT 信号启动它。我想要做的是传递值 X 到管道中使用的信号处理程序。此外,i 的值会在父进程运行期间发生变化,我将不得不多次传递它,所以我认为将其设为全局不会起作用。代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
void handler() {
//i would like to print the value of i here.
}
int main() {
int fd[2], s;
pipe(fd);
pid_t c = fork();
if (c == 0) {
signal(SIGINT, handler);
pause();
read(fd[0], &s, sizeof(s));
//if use printf("%d",s) here s=2 correctly.
}
if (c > 0) {
int i = 2;
sleep(1); //i don't want the SIGINT signal to terminate the child process so i wait for it to reach pause
kill(c, SIGINT);
write(fd[1], &i, sizeof(i));
}
}
怎么可能做到这一点?
解决方案
在子项的开头添加一个值为 0 的全局变量。在孩子中放置一个while循环。当信号到来时将其变为 1。在 while 循环中测试全局变量的值是否变为 1,如果是,则读取并打印并将变量返回为 0。
例子
#include <stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>
int signal_received = 0;
void handler(){
signal_received = 1;
}
int main(){
int fd[2],s;
pipe(fd);
pid_t c=fork();
if(c==0){
signal(SIGINT,handler);
while (1)
{
if (signal_received)
{
read(fd[0],&s,sizeof(s));
printf("%d",s);
signal_received = 0;
}
}
pause();
read(fd[0],&s,sizeof(s));
//if use printf("%d",s) here s=2 correctly.
}
if(c>0){
int i=2;
sleep(1);//i don't want the SIGINT signal to terminate the child process so i wait for it to reach pause
kill(c,SIGINT);
write(fd[1],&i,sizeof(i));
}
}
当然,这是您想要的存根,还有更多。
您可以在全局变量上添加并发保护。
如果您有一个更复杂的系统,那么消息队列会更合适。
希望能帮助到你 :)
推荐阅读
- java - 从使用 ClassLoader 加载源时,Apache Pdfbox 展平失败
- angular - Angular 默认路由器插座
- wpf - 如何防止孩子触发鼠标悬停事件?
- ubuntu - 使用vim时如何去除这个绿色区域?
- python-3.x - 未找到 gdal-config,Ubuntu 18.0.4,部署在 gcloud
- sql - 我想根据postgres sql中的给定容差对时间间隔进行分组
- react-native - 我如何打破钩子规则?
- c# - C#解析多个json
- apache - 如何使用 Apache mod_rewrite 将地址栏 URL 从 mysite.webhost.com 重写为 mysite.com
- python - 加载资源失败:服务器响应状态为 403(禁止)?