Linux編程--管道通信

系統調用函數read(),和write()的用法

write()函數對文件進行寫操作,函數原型爲
size_t write(int fd,const void* buf,size_t nbytes);
read()函數對文件進行讀操作
size_t read(int fd,const void* buf,size_t nbytes);
fd---文件描述符,buf---字符串指針  nbyte參數表示字節數,一個字節就是一個字符。

注意計算長度的時候:

strlen(buf)-----計算buf內容字符個數,到'\0'停止

sizeof(buf)----計算buf指針大小

管道通信例題分析---匿名管道間親緣關係通信(父子進程間)

#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<string>
/*father and son have pipe communication*/
using namespace std;
int main(){
    int pipe_fd[2];
    if(pipe(pipe_fd)<0){
        cout<<"pipe create wrong!"<<endl;
        return -1;
    }
    //father do something
    if(fork()>0){
        int r;
        char buf[16];
        cout<<"father wants read some from son"<<endl;
        r=read(pipe_fd[0],buf,sizeof(buf));
        buf[r]='\0';
        cout<<"father got string is "<<buf<<endl;
    }
    else{
    //son do something 
    
        const char *test="a testing string!";
        cout<<"son sleep"<<endl;
        sleep(5);
        cout<<"son writes after sleeping : "<<test<<endl;
        write(pipe_fd[1],test,strlen(test));
    
    }
    close(pipe_fd[0]);
    close(pipe_fd[1]);
    return 0;
}

運行結果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章