天天看点

创建一个管道,并实现其中的读写操作

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

int main()

{

 int fd[2];

 int nbytes;

 pid_t childpid;

 char string[] = "hello,Freeking/n";

 char readbuf[40];

 pipe( fd );

 if( ( childpid = fork()) == -1 )

 {

  perror( "fork error!" );

  exit(1);

 }

 if( childpid == 0 )

 {

  //子进程关闭管道的读句柄

  close( fd[0] ); 

  //通过写句柄向管道写入信息

  write( fd[1], string, strlen(string) );

  _exit(0);

 }

 else

 {

  //父进程关闭管道的读句柄

  close( fd[1] ); 

  //通过读句柄向管道读取信息

  nbytes = read(fd[0], readbuf, sizeof(string) );

  readbuf[nbytes] = '/0';

  printf( "Receive string: %s", readbuf );

 }

 return 0;

}