Demo entry 6652027

pipe.c

   

Submitted by anonymous on Oct 24, 2017 at 14:51
Language: C. Code size: 917 Bytes.

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>

int main(void){
   pid_t pid;
   int i=0;
   int result = -1;
   int fd[2],nbytes;
   char string[] = "你好,管道";//对string数组初始化
   char readbuffer[80];
   int *write_fd = &fd[1];
   int *read_fd = &fd[0];
   printf("Please input data:"); 
   scanf("%s",string);
   result = pipe(fd);
   if(-1 == result)
   {
      printf("建立管道失败!\n");
      return -1;
   }
   
   pid=fork();
   if(-1 == pid) //此处为了验证父子进程是否创建成功,如果未创建成功,则返回-1
   {
      printf("进程创建失败!\n");
      return -1;
   }
   else if(0 == pid)
   {
      close(*read_fd);
      result = write(*write_fd,string,strlen(string));
      return 0;
   }
   else
   {
      close(*write_fd);
      nbytes = read(*read_fd,readbuffer,sizeof(readbuffer)-1);
      printf("接收了%d个数据,内容为:\"%s\"\n",nbytes,readbuffer);
   }
return 0;
}

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).