你好,我有这样的问题

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的值,但主要是有正常的pids值。我怎么解决这个问题,谢谢你的帮助。

最佳答案

如果您想让孩子有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?
    }

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

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

10-11 21:30