作为练习,我编写了一个C程序来处理信号并对其进行计数等.然而,该程序本身实际上正在按预期"工作":
该程序多次使用fork(),首先创建一个子元素,然后再生成两个子元素(即顶级父级的孙辈).顶级父级等待子级完成,在此之前,子级等待其子级完成.
为了理解发生了什么,每次子代码执行时,我都会打印一条调试消息(以确保它只执行一次——如预期的那样).
这就是我得到的:
Note: Child PID: 28411
Note: Grandchild 2 PID: 28413
Note: Child PID: 28411
Note: Grandchild 1 PID: 28412
Note: Child PID: 28411
Grandchild with PID 28413 called SIGUSR2 1139226 times
Grandchild with PID 28412 called SIGUSR1 1140378 times
Print to console successful
All done!
[Done] exited with code=0 in 5.493 seconds
第一个子元素的电话是正确的,孙子孙女们也很好.然而,子代码for some reason会再执行两次.这也不是一个新的过程,因为PID是相同的.
我就是这样fork 元素的:
pid_t child = fork();
if (child == -1) {
perror("Failure to fork in main\n");
exit(-1);
}
else if (child == 0) {
childCode();
}
else {
wait(NULL);
}
我就是这样给孙子孙女们fork 的:
pid_t grandchild1 = fork();
if (grandchild1 == -1) {
// Error
perror("Failure to fork first grandchild");
}
else if (grandchild1 == 0)
// Grandchild
grandchildCode(1);
else {
// Child
pid_t grandchild2 = fork();
if (grandchild2 == -1) {
// Error
perror("Failure to fork second grandchild");
exit(-1);
}
else if (grandchild2 == 0) {
// Grandchild
grandchildCode(2);
}
else {
// Child
wait(NULL);
}
}
因为我不想用无用的代码把这个线程搞得乱七八糟,下面是Pastebin:https://pastebin.com/XnZEaaNZ (or should I include it here?)上的完整程序
我将非常感谢任何关于这方面的信息.我搞不懂.