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

1、read和write

1.2、read

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

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

1.3write

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

  #include 
 ssize_t write(int fd, const void *buf, size_t count);
 

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

2、pipe进程通信示例

#include 
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
#include
#include
#include
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;
}

在这里插入图片描述

你可能感兴趣的:(操作系统&&Linux)