pipeExample.c(向管道数据的简单读写操作)

/*
 *Author: 
 *Function: 利用pipe函数创建管道,并向其中写数据和从中读取数据
 */

#include
#include
#include
#include

#define BUFFERSIZE 1024


int main()
{
 int pipefd[2];    //定义管道的文件描述符
 int pipe_ret;
 ssize_t write_ret;
 ssize_t read_ret;
 char buf_in[BUFFERSIZE] = {"hello world"}; //输入缓冲区
 char buf_out[BUFFERSIZE] = {"0"}; //输出缓冲区


 
 //调用pipe函数创建管道,调用成功后pipe[1]作为读端,pipe[2]作为写端
 pipe_ret = pipe(pipefd);
 if(pipe_ret == -1)
 {
  perror("pipe error!");
  exit(-1);
 }

 write_ret = write(pipefd[1],buf_in,strlen(buf_in));
 if(write_ret == -1)
 {
  perror("write error!");
  exit(-1);
 }
 else
 {
  printf("write %d bytes!\n",write_ret);
 }

 read_ret = read(pipefd[0],buf_out,BUFFERSIZE);
 if(read_ret == -1)
 {
  perror("write error!");
  exit(-1);
 }
 else
 {
  printf("read %d bytes :%s\n",read_ret,buf_out);

 }

 return 0;
 
}

你可能感兴趣的:(linux代码)