linux 循环fork并等待其结束
2015-12-13 10:43
666 查看
fork子进程,在父进程里等待其结束,然后再fork下一个子进程,如此循环往复!
运行结果
[root@localhost training]# ./test
Parent waiting…
—Child 1 began.
Parent waiting…
Child 1 (pid:2795) ended.
Parent waiting…
—Child 2 began.
Parent waiting…
Child 2 (pid:2796) ended.
Parent waiting…
—Child 3 began.
Parent waiting…
Child 3 (pid:2797) ended.
cost 7 ms.
/* description: fork child process. * * * date : 2015/11/15 * * */ #include <stdio.h> #include <sys/wait.h> #include <sys/time.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char *argv[]) { struct timeval tvbegin, tvend; gettimeofday(&tvbegin, NULL); int i; for(i = 1; i <= 3; i++) { //-----------------fork child process int status; int child = fork(); if(child == -1) { printf("error\n"); } else if(child == 0) { printf("---Child %d began.\n", i); exit(0); } else { pid_t ret; do { ret = waitpid(child, &status, WNOHANG); printf("Parent waiting...\n"); usleep(1000); } while (ret == 0); printf("Child %d (pid:%d) ended.\n", i, child); } } gettimeofday(&tvend, NULL); printf("cost %d ms.\n", (tvend.tv_sec-tvbegin.tv_sec)*1000+(tvend.tv_usec-tvbegin.tv_usec)/1000); return 0; }
运行结果
[root@localhost training]# ./test
Parent waiting…
—Child 1 began.
Parent waiting…
Child 1 (pid:2795) ended.
Parent waiting…
—Child 2 began.
Parent waiting…
Child 2 (pid:2796) ended.
Parent waiting…
—Child 3 began.
Parent waiting…
Child 3 (pid:2797) ended.
cost 7 ms.
相关文章推荐
- Linux基础7 文件管理类命令
- Linux用户及权限管理
- linux-用户和用户组的设置(关于用户的一系列设置)
- Linux 用户管理命令
- 为什么 Linux Mint 比 Ubuntu好?
- Linux用户管理
- Linux学习笔记(二十四、VI编辑器概述)
- 武汉大学2013linux大作业
- Linux 常用快捷键
- linux下安装Mysql
- linux的“自动化”
- centos7与window10与window7三系统启动修改grup.cfg的方法
- centos7 安装极点五笔输入法的方法
- centos7中yum安装ntfs-3g
- centOS 安装mysql5.6
- centos7 install flash-plugin
- centos6.5 64位 搭建FTP服务器
- linux 同步IO: sync、fsync与fdatasync
- CentOS 7 在迷你系统上安装Gnome GUI图形界面
- Linux系统基础特性