c - 将值传递给子进程处理程序

标签 c operating-system

假设我通过 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 的全局变量。在 child 中放置一个 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));
}
}

当然,这只是您想要的 stub ,还有更多。

您可以对全局变量添加并发保护。

如果您有更复杂的系统,那么消息队列会更合适。

希望有帮助:)

关于c - 将值传递给子进程处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55303462/

相关文章:

C、进程、fork

c - 透明的 SQLite 数据压缩

循环输入错误后继续

Linux 内存使用量远大于所有应用程序使用内存的总和?

java - 为什么 mmap()(内存映射文件)比 read() 快

c - 使用二维数组在 C 中存储字符串

c - 警告 : suggest parentheses around assignment used as truth value [-Wparentheses]

java - File.length 平台和文件系统是否独立

c - 为什么在内核模式下执行回调函数不好?

android - 执行 os 命令 python 后获取打印值