fork函数分析举例
来源:互联网 发布:淘宝店铺简历和介绍 编辑:程序博客网 时间:2024/04/29 21:07
as we all know the exec() family function can only take the executable file to create a new process which replace the original one even the PID is the same to the original one, in contrast the fork funciton create a whole new process .the fork() function duplicates the current process , creating a new entry in the process table with many of the same attributes as the current process, the new process is almost identical to the original , executing the same code but with its own data space , environment , and file descriptors ,
#include <sys/types.h>#include <unistd.h>pid_t fok(void);
call to fork in the parent returns the PID of the new child process , the new process continues to execute just link the original , with the exception that in the child process the call to fork returns 0 ,and this allows both the parent and child to determine which is which .
and a typical code fragment using fork is
pid_t new_pid;new_pid=fork();switch(new_pid){ case -1:.........break; case 0:..........break;/*child process*/ default:.....break;/*parent process*/ }
now show you an example about it:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>int main(){pid_t num;char * mes;int n=0;int n1=1;int n2=1;printf("hello , are you ready\n");num=fork();switch(num){case -1:{printf("error\n");break;}case 0:{mes="child"; n1=5;n=5;break;}default:{mes="parent"; n2=3;n=2;break;}}for(int i=0;i<n1;i++){printf("%s--------%d\n",mes,getpid());sleep(1);}for(int i=0;i<n2;i++){printf("%s>>%d\n",mes,getpid());sleep(1);}printf("\n");for(int i=0;i<n;i++){printf("%s---%d",mes,i);sleep(1);}return 0;}
and the result is as follows:
0 0
- fork函数分析举例
- fork函数分析
- fork函数分析
- fork()函数的精辟分析
- fork()函数的精辟分析
- 关于fork()函数的分析
- fork()函数的精辟分析
- Linux中的fork()函数分析
- Linux中fork函数分析
- Linux中fork函数分析
- ORACLE 分析函数用法举例
- 简单的分析函数举例
- 简单的分析函数举例
- 关于fork()函数的精辟分析
- 关于fork()函数的精辟分析
- 关于fork()函数的精辟分析
- 关于fork()函数的精辟分析
- 关于fork()函数的精辟分析
- Struts旅程(三)Struts表单处理器ActionForm(静态动态)
- 获得windows系统相关图标
- 栈的应用实例--c程序括号的匹配
- HDU1171 Big Event in HDU
- iPad mini Retina越狱小结
- fork函数分析举例
- LiveRebel 3.0发布
- HDU1176 免费馅饼
- Android酱油笔记之EditText取消自动焦点
- HDU1224 Free DIY Tour
- HDU1231 最大连续子序列
- iOS Dev (46) iOS 的枚举
- OOP的三个核心本质之多态
- HDU1260 Tickets