进程间通信---在父进程跟子进程之间利用管道进行通信。一个简单的例子

#include <fcntl.h>								//提供open函数
#include <sys/types.h>                          // 该头文件提供系统调用的标志
#include <sys/stat.h>                           // 该头文件提供系统状态信息和相关函数
#include <sys/uio.h>                            // 该头文件提供进程I/O操作的相关函数
#include <unistd.h>                                     // 标准函数库
#include <fcntl.h>                                              // 文件操作相关函数库
#include <string.h>                                             // 字符串操作函数库
#include <sys/wait.h>                                   // wait调用相关函数库
#include <stdio.h>                                              // 标准输入与输出函数库
#include <stdlib.h>                                             // 常用工具函数库

int main() {
	int fd[2], len;
	char buf[200];
	pid_t cld_pid;
	if(pipe(fd) == -1) {
		puts("创建管道失败");
	}
	if((cld_pid = fork()) == 0) {        //zijincheng
		close(fd[1]);      //关闭写端口
		len = read(fd[0], buf, sizeof(buf));
		printf("1\n");
		buf[len] = '\0';
		printf("子进程从管道中读取的数据是:%s\n", buf);
		exit(0);
	} else {							//fujincheng
		close(fd[0]);     //关闭读端口
		printf("2\n");
		sprintf(buf, "zijinchengde pid shi %d", cld_pid);
		write(fd[1], buf, strlen(buf));
		exit(0);
	}
	return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值