当前位置: 技术问答>linux和unix
一个简单的FORK问题,请大虾指点
来源: 互联网 发布时间:2015-08-15
本文导语: #include #include #include int main() { pid_t pid; char *message; int n; int exit_code; printf("fork program startingn"); pid=fork(); switch(pid) { case -1: perror("...
#include
#include
#include
int main()
{
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork program startingn");
pid=fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message="This is a child";
n=5;
exit_code=37;
break;
default:
message="This is the parent";
n=3;
exit_code=0;
break;
}
for(;n>0;n--){
puts(message);
sleep(1);
}
if(pid=!0){
int stat_val;
pid_t child_pid;
child_pid=wait(&stat_val);
printf("Child has finished:PID=%dn",child_pid);
if(WIFEXITED(stat_val))
printf("child exited with code %dn",WEXITSTATUS(stat_val));
else
printf("child terminated abnormallyn");
}
exit(exit_code);
}
运行结果是这样的:
fork program starting
This is a child
This is the parent
This is the parent
This is a child
This is the parent
This is a child
This is a child
This is a child
Child has finished:PID=-1
child terminated abnormally
Child has finished:PID=7224
child exited with code 37
有两点很奇怪,怎么先出现一个child,然后连续出现两个parent,还有我明明知fork了一次,好像结果看来有两个子进程,而且一个意外地结束了,请大侠指点
#include
#include
int main()
{
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork program startingn");
pid=fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message="This is a child";
n=5;
exit_code=37;
break;
default:
message="This is the parent";
n=3;
exit_code=0;
break;
}
for(;n>0;n--){
puts(message);
sleep(1);
}
if(pid=!0){
int stat_val;
pid_t child_pid;
child_pid=wait(&stat_val);
printf("Child has finished:PID=%dn",child_pid);
if(WIFEXITED(stat_val))
printf("child exited with code %dn",WEXITSTATUS(stat_val));
else
printf("child terminated abnormallyn");
}
exit(exit_code);
}
运行结果是这样的:
fork program starting
This is a child
This is the parent
This is the parent
This is a child
This is the parent
This is a child
This is a child
This is a child
Child has finished:PID=-1
child terminated abnormally
Child has finished:PID=7224
child exited with code 37
有两点很奇怪,怎么先出现一个child,然后连续出现两个parent,还有我明明知fork了一次,好像结果看来有两个子进程,而且一个意外地结束了,请大侠指点
|
这个程序不是自己写的吧?
1.fork一次多出一个子child进程,加上原来那个parent进程,共两个对吧,child进程中n=5,parent进程中n=3,所以分别打印"This is XXXX"5次和3次,因为两个进程统一通过内核调度,所以打印出的信息一般是交替出现
2.你把if(pid=!0)改成if(pid != 0)再试试看,至于原因你自己想吧
1.fork一次多出一个子child进程,加上原来那个parent进程,共两个对吧,child进程中n=5,parent进程中n=3,所以分别打印"This is XXXX"5次和3次,因为两个进程统一通过内核调度,所以打印出的信息一般是交替出现
2.你把if(pid=!0)改成if(pid != 0)再试试看,至于原因你自己想吧
|
gcc 的时候把-Wall 打开可以避免很多比较低级的错误,这是一个比较好的习惯:)
|
两个进程的调度嘛就没有什么规律了。
|
两个进程交替被调度运行,打印的当然没有什么规律。
|
http://imit.vicp.net/linux.htm