linux中用管道实现父子进程通信
2024-08-30 14:49:42
1 用户要实现父进程到子进程的数据通道,可以在父进程关闭管道读出一端,
然后相应的子进程关闭管道的输入端。
2 先用pipe()建立管道 然后fork函数创建子进程。父进程向子进程发消息,子进程读消息。
3 实现
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#define BUFSZ PIPE_BUF /*PIPE_BUF管道默认一次性读写的数据长度*/
int main ( void )
{
int fd[];
char buf[BUFSZ];
pid_t pid;
ssize_t len;
if ( (pipe(fd)) < ){ /*创建管道*/
perror ( "failed to pipe" );
exit( );
}
if ( (pid = fork()) < ){ /* 创建一个子进程 */
perror ( "failed to fork " );
exit( );
}
else if ( pid > ){
close ( fd[] ); /*父进程中关闭管道的读出端*/
write (fd[], "hello tian chaoooo!\n", ); /*父进程向管道写入数据*/
exit ();
}
else {
close ( fd[] ); /*子进程关闭管道的写入端*/
len = read (fd[], buf, BUFSZ ); /*子进程从管道中读出数据*/
if ( len < ){
perror ( "process failed when read a pipe " );
exit( );
}
else
write(STDOUT_FILENO, buf, len); /*输出到标准输出*/
exit();
}
}
4 截图
最新文章
- linux搭载discuz
- Golang Clearing slice
- c#调用系统资源大集合-3
- Java [Leetcode 235]Lowest Common Ancestor of a Binary Search Tree
- Powerpoin怎么制作电子相册|PPT制作电子相册教程
- 在win7 64bit系统安装QC软件
- PAT1027
- Oracle执行计划顺序
- Educational Codeforces Round 21(A.暴力,B.前缀和,C.贪心)
- [博客迁移]探索Windows Azure 监控和自动伸缩系列2 - 获取虚拟机的监控定义和监控数据
- VMware14安装centos7
- Android 本地播放器
- vs2017诊断工具
- DataContractSerializer数据不一致下序列化
- springboot整合Mybatis(一)——入门
- javascript日期字符串和日期对象相互转换
- C语言程序员必读的5本书
- ubuntun16.0 登陆密码忘记
- B树, B-树,B+树,和B*树的区别
- 【转】Jenkins+Ant+Jmeter自动化性能测试平台
热门文章
- ImportError: No module named _curses;Color support is disabled, python-curses is not installed.解决办法
- 在windows中增加linux命令
- 查询mysql字段名和字段注释
- 线程池ThreadPoolExecutor分析
- iOS提交应用至App Store流程及真机调试 一,证书、配置文件
- (转)C中的volatile用法
- Redis实现消息的发布/订阅
- Handler之IdleHandler
- collection 模块 双端队列
- dubbo简单配置与使用