创建进程fork()函数使用

来源:互联网 发布:小说阅读软件哪个好 编辑:程序博客网 时间:2024/06/04 17:46
 由f o r k函数创建的新进程被称为子进程.该函数被调用一次,但返回两次。 
两次返回的区别是子进程的返回值是0,而父进程的返回值则是新子进程的进程I D。 
一般的来说,在f o r k之后是父进程先执行还是子进程先执行是不确定的。这取决于内核所使用的调度算法。 
 1 #include <unistd.h>

      2 #include <sys/types.h>

      3 void main(void)

      4 {

      5   pid_t pid;

      

      7   pid=fork();

      

      9   if(pid < 0)

     10   {

     11      printf("error in fork!\n");

     12   }

     13   else if(pid == 0)

     14   {

     15      printf("in child return pid value is = %d\n",(int)pid);

     16      printf("i am the child process,my process id is %d\n",getpid());

     17      printf("i am the child process,my parent id is %d\n",getppid());

     18   }

     19   else

     20   {

     21      printf("in father return pid value is = %d\n",(int)pid);

     22      printf("i am the parent process,my process id is %d\n",getpid());

     23      printf("i am the parent process,my parent id is %d\n",getppid());

     24   }

     25 }

结果:

1root@darkstar:/home/zhangl/unixtest/chapter8# ./testfork    

in father return pid value is = 1293

i am the parent process,my process id is 1292

i am the parent process,my parent id is 1229

root@darkstar:/home/zhangl/unixtest/chapter8# in child return pid value is = 0

i am the child process,my process id is 1293

i am the child process,my parent id is 1

2root@darkstar:/home/zhangl/unixtest/chapter8# ./testfork

in father return pid value is = 1328

i am the parent process,my process id is 1327

i am the parent process,my parent id is 1301

in child return pid value is = 0

i am the child process,my process id is 1328

i am the child process,my parent id is 1

3root@darkstar:/home/zhangl/unixtest/chapter8# ./testfork

in father return pid value is = 1373

in child return pid value is = 0

i am the child process,my process id is 1373

i am the child process,my parent id is 1372

i am the parent process,my process id is 1372

i am the parent process,my parent id is 1354

原创粉丝点击