你好,我有这样的问题
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);
}
所以我需要在我的信号回调中有 pid1
和 pid2
的值,在 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/