C 保存 fork 的 pid

标签 c signals fork

你好,我有这样的问题

pid_t pid1;
pid_t pid2;

void switch_files(int sig_type)
{
    printf("%d %d\n", pid1, pid2);
}
int main(int argc, char **argv)
{
    pid_t lpid1,lpid2;        
    if ((lpid1 = fork()) == 0)
    {
        signal(SIGUSR1, switch_files);
      //Some work   
    } else {
        pid1 = lpid1;
    }
    if ((lpid2 = fork()) == 0)
    {
        signal(SIGUSR2, switch_files);
        //Some work

    } else {
        pid2 = lpid2;
    }


    while(scanf("%s", input) > 0)
    {
        write(pipe1[1], input, strlen(input) + 1);
        kill(pid1, SIGUSR1);
    }

    waitpid(pid1, 0, 0);
    waitpid(pid2, 0, 0);
}

所以我需要在我的信号回调中有 pid1pid2 的值,在 printf 中我有 0 0 但在 main我有正常的 pids 值。我该如何解决这个问题,感谢您的帮助。

最佳答案

如果您想让 child 拥有 pid,只需请求它:

if ((lpid1 = fork()) == 0)
    {
        pid1 = getpid();
        pid2 = -1; // other child doesn't even exist yet
        signal(SIGUSR1, switch_files);
        //Some work
        exit(0); // you don't want the child to go executing parent code, do you?
    }

if ((lpid2 = fork()) == 0)
    {
        //pid1 already set with pid of 1st child
        pid2 = getpid();
        signal(SIGUSR2, switch_files);
        //Some work
        exit(0); // you don't want the child to go executing parent code, do you?
    }

如果您需要第一个 child 拥有第二个 child 的 pid,那么您需要使用 some form of IPC ,这样您就可以在第二个 child 也已启动且其 pid 已知后与第一个 child 通信。

关于C 保存 fork 的 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821698/

相关文章:

php - 如何中断exec并杀死子进程

python - 使异步事件循环响应 Windows(和 Unix)上的 KeyboardInterrupt

c++ - Qt C++ : Linking multiple instances of a QPushButton subclass using Signals/Slots

在 C 中使用位打包压缩 'char' 数组

c - 在c中用struct提取位域

c - 来自一个父进程的多个子进程

Python:进程被杀死后多次打印到控制台

c - UNIX fork() 之后的 printf()

python - 告诉 zlib python 是用什么版本构建的

c - gnu 库 C 中的 libc_hidden_​​proto 宏