标题: fork()的奇怪问题。请赐教 [打印本页] 作者: baiyoung 时间: 2006-08-29 16:58 标题: fork()的奇怪问题。请赐教 小弟不才,新学linux C 程序设计,抄了一份C程序,输出的结果怎么和预期的不一样?请指教
预期:
输出5次:This is child
输出3次:this is the parent
结果:
一直无穷尽输出下去
=====================================
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main (int argc, char * argv[])
{
pid_t pid;
char *message = 0;
message = (char *)malloc(sizeof(char) * 100);
int n;
printf("fork Programming start\n");
pid = fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(0);
case 0:
message="This is child";
n = 5;
break;
default :
message = "this is the parent";
n = 3;
break;
}
for(; n > 0; n++)
{
puts(message);
sleep(1);
}
free(message);
message = 0;
exit(0);
}作者: baiyoung 时间: 2006-08-29 17:04
自己把问题解决了,习惯性的错误
for(; n > 0; n--)
{
puts(message);
sleep(1);
}作者: sithui 时间: 2006-08-29 17:11
你得到正确的结果了吗?作者: baiyoung 时间: 2006-08-29 17:31
嗯
当然是顺序与我上面说得不一样了
fork Programming start
This is child
this is the parent
This is child
this is the parent
this is the parent
This is child
/home/ibas6/wanglu$This is child
This is child作者: coldwarm 时间: 2006-08-29 17:58