所以我今天一直在努力,我很确定我很接近,但是我仍然对如何终止子进程以及我是否正确地执行此任务感到困惑。这是问题描述:
Write a UNIX program that creates a child process that
prints a greeting, sleeps for 20 seconds, then exits.
The parent process should print a greeting before creating
the child, and another after the child has terminated. It
should then terminate.
这是我的代码:
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int child;
printf("Parent Greeting\n");
child = fork();
if(child >= 0)
{
if(child == 0)
{
printf("Child process\n");
sleep(2);
printf("Child exiting\n");
exit(0);
}
}
else
{
printf("Failed\n");
}
printf("End");
exit(1);
return 0;
}
我遇到的问题是如何正确终止子进程。如果我将退出语句注释掉,那么子项将运行,等待,然后将打印“结束”语句。如果我有退出语句,那么子进程会说它正在退出,程序将只是坐下来直到我ctrl + c出来。任何帮助将不胜感激,因为我对这个主题感兴趣,但有点困惑:)谢谢!
答案 0 :(得分:7)
您不必从父级终止子进程;它应该自行终止(并且在sleep()
,printf()
和exit()
之后。在打印"End"
消息之前,父进程应该wait()
or waitpid()
让孩子死掉。此外,您的"End\n"
邮件应包含换行符。
不需要exit(1);
(在第一个程序结束时);它表示失败。 exit()
函数未返回,因此写入时return
是多余的。但最好删除exit()
并保留return 0;
表示成功。
(请注意,孩子应该包括对exit()
的调用,可能是修改后的代码中的值为0而不是1。毕竟,它已成功完成其工作。)
答案 1 :(得分:1)
问题是您已经强制父进程在子进程之前退出,在这种情况下,子进程不再成为僵尸进程,并且在某个时候出现ghost进程,在结束之前添加wait()最后退出。
答案 2 :(得分:0)
我认为这正是你想要实现的目标。
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
void err_sys(const char* x)
{
perror(x);
exit(1);
}
int main()
{
pid_t childPid;
printf("Parent greeting\n");
childPid =fork();
if (childPid >=0)
{
if(childPid == 0)
{
printf("Child process\n");
sleep(20);
printf("child exiting\n");
}
else
{
waitpid(-1,NULL,0);
}
}
else
{
err_sys("fork error\n");
}
printf("END\n");
return 0;
}