首页 > 解决方案 > 将值传递给子进程处理程序

问题描述

假设我通过 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));
    }
}

怎么可能做到这一点?

标签: coperating-system

解决方案


在子项的开头添加一个值为 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));
}
}

当然,这是您想要的存根,还有更多。

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

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

希望能帮助到你 :)


推荐阅读