1. 程式人生 > >linux程式設計——管道操作

linux程式設計——管道操作

#include <iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/fcntl.h>
#include<unistd.h>
#include<cstring>
#include<sys/wait.h>
using namespace std;

int main(int argc, char *argv[])
{
   int result=-1;
   int fd[2],nbyte;

   pid_t pid;
   char  str[]="hello,world";
   char str_recv[100];
     result=pipe(fd);
   int read_pipe=fd[0];        //這裡有個坑,一開始我把讀管道設定成了fd[1],寫設定成了fd[0]
   cout<<"read_pipe is  "<<read_pipe<<endl;
   int write_pipe=fd[1];     //管道的設定有嚴格的順序,fd[0]才是讀   fd[1]才是寫
    cout<<"write_pipe is  "<<write_pipe<<endl;


   pid=fork();  //建立一個程序
   if(pid==-1)
   {
       perror("pid:error");
   }

   if(pid==0)   //子程序
   {
       cout<<"11111"<<endl;
       close(read_pipe);
       cout<<"str is "<<str<<endl;
       result=write(write_pipe,str,strlen(str));
       cout<<"write result value is "<<result<<endl;

       return 0;

   }
   if(pid>0)  //父程序
   {
         wait(NULL);    //等待子程序結束
       close(write_pipe);
       memset(&str_recv,0,sizeof(str_recv));
       nbyte=read(read_pipe,str_recv,sizeof(str_recv));
       cout<<"recv "<< nbyte  <<" data,data is text :  "<<str_recv <<endl;
   }
   return 0;

}

ps:當管道的寫端沒有關閉時,寫請求的位元組數目大於閾值PIPE_BUF(在include/linux/limits.h中可以檢視),寫操作的返回值是管道中目前的資料位元組數。如果請求的位元組數(讀管道)不大於PIPE_BUF,則返回管道中的現有位元組數(管道中資料量小於請求資料量),或者返回請求的位元組數(管道中資料量不小於請求的資料量)

 

當寫入的資料大於128K時,緩衝區的資料將被持續寫入管道,如果沒有程序讀取,則會一直阻塞