父子进程 使用管道通信示例

1、read和write

1.2、read

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
状态返回值
成功返回实际读的字节数
错误-1
读取时已经到达文件的末尾0

在成功读取时:
如果还没达到count想要读的字节数,就已经到达结尾,实际返回值0<x<count;
如果达到了count值,仍没达到文件结尾,,返回值为count.

1.3write

将buf所指的内存中的count个字节,写入到文件描述符fd所指的文件中去。

  #include <unistd.h>
 ssize_t write(int fd, const void *buf, size_t count);
 

返回值:成功返回写入的字节数,失败返回-1

2、pipe进程通信示例

#include <unistd.h>
int pipe(int pipefd[2]);

pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication.
The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0]
refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe. Data written to
the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe.
For further details, see pipe(7).

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
	int fd[2];
	pid_t  pid;
	int ret =pipe(fd);
    if(ret==-1){
	  perror("pipe error\n");
	  exit(1);
	} 
	pid=fork();
	if(pid<0){
	  perror("error\n");
	  exit(1);
	}
	else if(pid>0){
	//父进程  写操作,关闭读端  	  
	  close(fd[0]); 
	  write(fd[1],"hello pipe\n",strlen("hello pipe\n"));
	  sleep(1);
	}
	else {
	//子进程  读操作,关闭写端
	  close(fd[1]);
	  char buf[1024];
	  ret =read(fd[0],buf,sizeof(buf));
	  if(ret==0){//read的返回值,为0说明未度到内容
		printf("未能读到内容\n");
	  }
	  write(STDOUT_FILENO,buf,ret);
	}
	if(pid>0)
	printf("父进程即将结束\n");
	if(pid==0)
	printf("子进程即将结束\n");
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值