首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

fork函数使用的疑问?该怎么解决

2012-02-19 
fork函数使用的疑问??????#includesys/types.hmain(){inti5pid_tpidpidfork()for(i 0i--){if(pi

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;
你又没加互斥之类的,二进程轮着进行就出现这结果了。

热点排行