我应该如何修改 C 中的 fork() 以使其运行良好?
我不明白为什么我的代码不起作用。
这是我的代码。 我不知道为什么会出现错误段。 有人可以向我解释一下原因吗?
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
int id_process;
void manager_signal () {
kill (id_process, SIGKILL);
kill (getppid(),SIGKILL);
}
int main () {
id_process = fork ();
if (id_process==-1) {
perror("ERROR to create the fork");
} else {
if ( id_process != 0 ) {
printf("Father´s ID is %d \n", getpid());
alarm(5);
(void) signal (SIGALRM, manager_signal);
sleep (20);
printf ("Running to where the father can be\n");
alarm (0);
} else {
printf ("CHildren´s ID is %d \n", getpid ());
for (;;) {
printf ( "Children RUN FOREVER ^^");
sleep (2);
}
}
}
return 0;
}
I dont understand why my code does not work.
This is my code. I don't know why I'm get an error segment. Could somebody explain the reason to me?
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
int id_process;
void manager_signal () {
kill (id_process, SIGKILL);
kill (getppid(),SIGKILL);
}
int main () {
id_process = fork ();
if (id_process==-1) {
perror("ERROR to create the fork");
} else {
if ( id_process != 0 ) {
printf("Father´s ID is %d \n", getpid());
alarm(5);
(void) signal (SIGALRM, manager_signal);
sleep (20);
printf ("Running to where the father can be\n");
alarm (0);
} else {
printf ("CHildren´s ID is %d \n", getpid ());
for (;;) {
printf ( "Children RUN FOREVER ^^");
sleep (2);
}
}
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题有点难以理解,因为您没有真正解释错误是什么,但我确实有一个问题,我确信这是相关的。
为什么“父亲”进程会杀死其子进程及其父进程? 难道它不应该杀死它的孩子和它自己(
id_process
和getpid()
而不是getppid()
这是父PID)吗?这似乎就是问题所在。 当我在 Cygwin 下运行它时,它会杀死我的 shell(真烦人)。 如果我将其更改为
kill (getpid(),SIGKILL);
,它会在五秒后正常终止,并显示以下输出:这是程序修改后的情况,如下所示:
Your question is a little difficult to understand since you don't really explain what the error is, but I do have one question which I'm sure will be pertinent.
Why is the "father" process killing its child and its parent? Shouldn't it kill its child and itself (
id_process
andgetpid()
rather thangetppid()
which is the parent PID)?That appears to be the problem. When I run that under Cygwin, it kills off my shell (darned annoying). If I change it to
kill (getpid(),SIGKILL);
, it terminates okay after five seconds with the following output:This is with the program modified as follows:
我认为
也没有必要。 您将在下一条指令中终止相同的进程。
I don't think
is required either. You're killing the same process in the next instruction.