linux进程的学习

来源:互联网 发布:基础设施投资数据 编辑:程序博客网 时间:2024/06/05 22:41


#include <stdio.h>#include <unistd.h>#include <sys/types.h>void delay(int x){int i=0;while(x--) for(i=0;i<1010;i++);}int main (){pid_t child_pid;child_pid = fork();

//fork函数调用以后父亲进程返回的是子进程的pid,而子进程返回的是0,所以可以通过区分PID的值来区分父子进程的代码//从这个地方开始代码开始复制一遍并执行switch(child_pid){ case -1: printf("Create Process Failed!\n"); break; case 0:printf("Child Process with ID %d!\n", (int) getpid()); break; default: printf("Parent Process with ID %d, Child Process ID %d!\n", (int) getpid(), (int) child_pid); break;}return 0;}

运行结果:
Parent Process with ID 3718, Child Process ID 3723!
Child Process with ID 3723!
分析:
在执行fork函数创建进程的时候,fork函数之后的代码复制一份,并且fork函数返回值child_pid,在父亲进程中child_pid是子进程的PID而在子进程中child_pid为0,通过这个值的不同可以区分父子进程的不同执行代码,即代码相同但是执行选择的分支不同而已。一般选用case语句来区分父子进程的不同。
0 0
原创粉丝点击