进程间pipe通信
2015-12-13 11:18
393 查看
开始循环fork子进程,每个子进程等待前一个子进程结束后才结束
运行结果
[root@localhost training]# ./test
—-child:2 began.
—-child:3 began.
—-child:1 began.
—-child:1 ended.
—-child:2 ended.
—-child:3 ended.
all complete!
cost 2 ms
/* description: communicate between child process and parent processes * * fork every child process and arrange them being ended in order. * * date : 2015/11/23 * * */ #include <stdio.h> #include <sys/time.h> #include <unistd.h> #include <malloc.h> #include <string.h> #include <stdlib.h> int number = 3; //-----------------for pipe communication char cmdBegin[10] = "begin"; char cmdEnd[10] = "end"; int main(int argc, char *argv[]) { // calculate running time struct timeval tvbegin, tvend; gettimeofday(&tvbegin, NULL); //-----------------pipe int (* fd) [2] = (int (*)[2]) malloc (sizeof(int) * 2 * number); if(pipe(fd[0]) < 0) { printf("pipe [0] error\n"); exit(1); } write(fd[0][1], cmdEnd, strlen(cmdEnd)); int iChild; for(iChild = 0; iChild < number; iChild++) { if(pipe(fd[iChild]) < 0) { printf("pipe [%d] error\n", iChild); exit(1); } int child = fork(); if(child == -1) { printf("fork [%d] child process error\n", iChild); } else if(child == 0) { printf ("----child:%d began.\n", iChild + 1); //-----------------wait the front child process to end if(iChild > 0) { close(fd[iChild - 1][1]); char cmd [10] = {0}; read(fd[iChild - 1][0], cmd, sizeof(cmd)); while(strcmp(cmd, cmdEnd) != 0) { usleep(10); read(fd[iChild - 1][0], cmd, sizeof(cmd)); } } //-----------------write the pipe close(fd[iChild][0]); write(fd[iChild][1], cmdEnd, strlen(cmdEnd)); printf ("----child:%d ended.\n", iChild + 1); exit(0); } } //-----------------wait the last child process to end close(fd[iChild - 1][1]); char cmd [10] = {0}; read(fd[iChild - 1][0], cmd, sizeof(cmd)); while(strcmp(cmd, cmdEnd) != 0) { usleep(10); read(fd[iChild - 1][0], cmd, sizeof(cmd)); } printf ("all complete!\n"); free(fd); 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
—-child:2 began.
—-child:3 began.
—-child:1 began.
—-child:1 ended.
—-child:2 ended.
—-child:3 ended.
all complete!
cost 2 ms
相关文章推荐
- C# 小例子(1)
- compan--生成友矩阵
- ubuntu 14.04 NFS服务器的搭建
- 1800: 少水群多刷题
- 千里码oj_老王装货
- Codeforces Round #335 (Div. 2)
- 有关solaris fmd服务下的命令fmdump的简单使用
- 移动开发的福音,BaaS后端云服务
- Lobes of the brain
- 二叉树反转(java版)
- 关于数组中的值拼接成字符串中间用逗号隔开的实现
- toeplitz--生成托普利兹矩阵
- POJ 2242|ZOJ 1090 The Circumference of the Circle
- Log4j2介绍和特性实例(二)--一个实例和初学注意事项(configuration标签中的 status 和 monitorInterval)
- 关于权限控制的讨论:操作与数据
- Android 启动模拟器是出现“Failed to allocate memory: 8”错误提示的原因及解决办法
- pascal--生成Pascal矩阵
- AngularJs实战(四)
- 接口回调的使用方法
- Javaweb工程找不到jquery问题