fork函数使用的疑问??????
#include <sys/types.h>
main ()
{
int i=5;
pid_t pid;
pid=fork();
for(;i> 0;i--)
{
if (pid < 0)
printf( "error in fork! ");
else if (pid == 0)
printf( "i am the child process, my process id is %d and i=%d\n ",getpid(),i);
else
printf( "i am the parent process, my process id is %d and i=%d\n ",getpid(),i);
}
for(i=5;i> 0;i--)
{
if (pid < 0)
printf( "error in fork! ");
else if (pid == 0)
printf( "the child process, my process id is %d and i=%d\n ",getpid(),i);
else
printf( "the parent process, my process id is %d and i=%d\n ",getpid(),i);
}
}
这个程序怎么会有这样的结果?
i am the child process, my process id is 4293 and i=5
i am the child process, my process id is 4293 and i=4
i am the child process, my process id is 4293 and i=3
i am the child process, my process id is 4293 and i=2
i am the child process, my process id is 4293 and i=1
the child process, my process id is 4293 and i=5
the child process, my process id is 4293 and i=4
i am the parent process, my process id is 4292 and i=5
i am the parent process, my process id is 4292 and i=4
i am the parent process, my process id is 4292 and i=3
the child process, my process id is 4293 and i=3
the child process, my process id is 4293 and i=2
the child process, my process id is 4293 and i=1
i am the parent process, my process id is 4292 and i=2
i am the parent process, my process id is 4292 and i=1
the parent process, my process id is 4292 and i=5
the parent process, my process id is 4292 and i=4
the parent process, my process id is 4292 and i=3
the parent process, my process id is 4292 and i=2
the parent process, my process id is 4292 and i=1
[解决办法]
是多进程的原因;
fork函数被调用一次,返回二次,二次返回值区别是子进程的返回值是0,父进程返回的是子进程ID;
你又没加互斥之类的,二进程轮着进行就出现这结果了。