fork系统调用

来源:互联网 发布:网络教育哪些学校好 编辑:程序博客网 时间:2024/05/22 16:13

/* * simple fork usage */#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main(){pid_t child;if ((child = fork()) == -1){perror("fork");exit(EXIT_FAILURE);}else if(child == 0){puts("in child");printf ("\tchild pid = %d\n", getpid());printf ("\tchild ppid = %d\n", getppid());exit(EXIT_SUCCESS);}else{puts("in parent");printf ("\tparent pid = %d\n", getpid());printf ("\tparent ppid = %d\n", getppid());}return (EXIT_SUCCESS);}


-----------------------------------------------

第一次运行结果如下:

in parent

in child
parent pid = 4836
parent ppid = 4835
child pid = 4837

child ppid = 4836

----------------------------------------------

第二次运行结果变这样了:


in parent
parent pid = 4855
in child
parent ppid = 4854
child pid = 4856
child ppid = 4855

使用fork时, 夫进程和子进程的运行顺序是随机的,也就是说他的执行是异步的。