Pau*_*uiz 2 c unix operating-system process
所以今天我一直在努力,我很确定我很接近,但我仍然对如何终止子进程以及我是否正确地执行此任务感到困惑.这是问题描述:
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.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是如何正确终止子进程.如果我将退出语句注释掉,那么子项将运行,等待,然后将打印"结束"语句.如果我有退出语句,那么子进程会说它正在退出,程序将只是坐下来直到我ctrl + c出来.任何帮助将不胜感激,因为我对这个主题感兴趣,但我有点困惑:)谢谢!
您不必从父级终止子进程; 它应该自行终止(与后确实sleep(),printf()和exit()).父进程应该wait()或者waitpid()在打印"End"消息之前让孩子死掉.此外,您的"End\n"邮件应包含换行符.
的exit(1);(在第一个节目的结束时)是不想要; 它表示失败.该exit()函数不返回,因此写入return是冗余的.但最好删除exit()并留下return 0;指示成功.
(注意,孩子应该包括一个调用exit(),可能是修改后的代码中的值为0而不是1.毕竟,它已成功完成了它的工作.)
| 归档时间: |
|
| 查看次数: |
8587 次 |
| 最近记录: |