您的位置:首页 > 其它

创建进程fork()函数使用

2011-08-08 16:00 441 查看
由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;
6
7 pid=fork();
8
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 }
结果:
1,root@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
2,root@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
3,root@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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: