【发布时间】:2015-12-23 05:28:33
【问题描述】:
我想编写一个创建N 子进程的 UNIX 程序,这样第一个进程创建一个子进程,然后这个子进程只创建一个作为其子进程的进程,然后该子进程的子进程创建另一个子进程,等等.
这是我的代码:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N=3;
int i=0;
printf("Creating %d children\n", N);
printf("PARENT PROCESS\nMy pid is:%d \n",getpid() );
for(i=0;i<N;i++)
{
pid_t pid=fork();
if(pid < 0)
{
perror("Fork error\n");
return 1;
}
else if (pid==0) /* child */
{
printf("CHILD My pid is:%d my parent pid is %d\n",getpid(), getppid() );
}
else /* parrent */
{
exit(0);
}
}
return 0;
}
我期望的输出是这样的:
Creating 3 children
PARENT PROCESS
My pid is 1234
CHILD My pid is 4567 my parent pid is 1234
CHILD My pid is 3528 my parent pid is 4567
CHILD My pid is 5735 my parent pid is 3528
我在终端得到的输出是
Creating 3 children
PARENT PROCESS
My pid is:564
CHILD My pid is:5036 my parent pid is 564
User@User-PC ~
$ CHILD My pid is:4804 my parent pid is 1
CHILD My pid is:6412 my parent pid is 4804
问题是程序似乎没有终止。我应该使用Ctrl+C 退出终端,这是不正常的。你能帮我解决这个问题吗?
【问题讨论】:
-
编译时必须有
warning: implicit declaration of function ‘exit’。尝试添加#include <stdlib.h>
标签: c unix operating-system fork