[置顶] Linux高编之进程--------fork函数的同步与异步(兄弟子进程和父子孙进程示列)
2013-10-08 21:32
489 查看
前面讲述的fork函数的基本用法,下面通过两个程序来说明fork函数同步与异步之间的关系:
<1>通过fork函数实现在父进程下的四个兄弟子进程(即异步) :
函数实现代码:
用工具pstree观察如下图:
可以看到有三个a.out并列,即他们直接属于兄弟进程。
<2>通过fork函数实现在父进程下的父子孙进程(即同步):
函数代码如下:
用pstree观看如下:
可知他们之间是父子孙进程,是同步关系。
通过以上我们了解了fork函数同步与异步之间大的差异,又不正确的地方希望指正。。。。
<1>通过fork函数实现在父进程下的四个兄弟子进程(即异步) :
函数实现代码:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <sys/wait.h> int main (void) { pid_t pid; char *message; int i; for(i=0;i<3;i++){ pid=fork(); if(pid==0)break; } if(pid<0){ perror("fork failed"); exit(1); } if(pid==0){ int i; for(i=5;i>0;i--){ printf("pid=%d\tpid=%d\n",getpid(),getppid()); printf("This is the child\n"); sleep(1); while(1); } exit(3); } else{ int stat_val; waitpid(pid,&stat_val,0); // wait(&stat_val); if(WIFEXITED(stat_val)) printf("Child exited with code %d\n",WEXITSTATUS(stat_val)); else if(WIFSIGNALED(stat_val)) printf("Child terminated abnormally,signal %d\n",WTERMSIG(stat_val)); } return 0; }
用工具pstree观察如下图:
可以看到有三个a.out并列,即他们直接属于兄弟进程。
<2>通过fork函数实现在父进程下的父子孙进程(即同步):
函数代码如下:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <sys/wait.h> int main (void) { pid_t pid; char *message; int i; for(i=0;i<3;i++){ pid=fork(); if(pid>0)break; } if(pid<0){ perror("fork failed"); exit(1); } if(pid==0){ int i; for(i=5;i>0;i--){ printf("pid=%d\tpid=%d\n",getpid(),getppid()); printf("This is the child\n"); sleep(1); //while(1); } exit(3); } else{ int stat_val; waitpid(pid,&stat_val,0); // wait(&stat_val); if(WIFEXITED(stat_val)) printf("Child exited with code %d\n",WEXITSTATUS(stat_val)); else if(WIFSIGNALED(stat_val)) printf("Child terminated abnormally,signal %d\n",WTERMSIG(stat_val)); } return 0; }
用pstree观看如下:
可知他们之间是父子孙进程,是同步关系。
通过以上我们了解了fork函数同步与异步之间大的差异,又不正确的地方希望指正。。。。
相关文章推荐
- Linux高编之进程--------fork函数的同步与异步(兄弟子进程和父子孙进程示列)
- Linux中fork()函数详解 父子进程变量的关系
- Linux 内核--fork()函数创建进程
- Linux下的多进程编程(转) - fork(),exec()等函数的使用[zz]
- Linux进程的创建函数fork()及其fork内核实现解析
- Linux 内核--fork()函数创建进程 (续)之copy_mem(int nr, struct task_struct *p)
- linux系统编程之进程(二):fork函数相关总结
- linux系统下 fork()系统调用: 关于父子进程缓存问题的小坑
- Linux中fork的使用(03)---使用if...else...区分父子进程特有的内容
- linux进程编程(一)-- fork()函数简单应用
- [置顶] 每天进步一点点——论fork()函数与Linux中的多线程编程
- 【Linux编程】进程标识符与fork函数
- Linux -- 进程管理之fork() 函数
- [置顶] linux中fork()函数详解 ) http://blog.csdn.net/jason314/article/details/5640969
- 《王保明老师----Linux开发学习笔记》------讲03:进程 -----fork( )函数的一点理解
- 操作系统(Linux)---fork()函数解析与进程
- Linux进程函数fork(),vfork(),execX()的深入理解
- 【linux进程】fork函数浅析
- linux 中的进程wait()和waitpid函数,僵尸进程详解,以及利用这两个函数解决进程同步问题
- Linux 进程学习1 --fork()函数