Linux學習筆記——管道PIPE

來源:互聯網
上載者:User

管道:當從一個進程串連資料流到另一個進程時,使用術語管道(pipe)。

# include <unistd.h>
int pipe(int filedes[2]); //建立管道

pipe()說明:
傳回值:0成功,-1出錯。
如果調用成功,則進程此時由了兩個額外的開啟檔案描述符,filedes[0]中的值是管道的讀取端,而filedes[1]是管道的寫入端。

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

int main(){
    int pipe_fd[2];
    pid_t pid;
    char buf_r[100];
    char *p_wbuf;
    int r_num;

    memset(buf_r,0,sizeof(buf_r));

    //建立管道
    if(pipe(pipe_fd)<0){
        printf("pipe create error/n");
        return -1;
    }

    if((pid=fork())==0){//表示在子進程中
        printf("/n");
        //關閉管道寫描述符,進行管道讀操作
        close(pipe_fd[1]);
        sleep(2);
        //管道描述符中讀取
        if((r_num=read(pipe_fd[0],buf_r,100))>0){
            printf("%d numbers read from the pipe is %s/n",r_num,buf_r);
        }
        close(pipe_fd[0]);
        exit(0);
    }
    else if(pid>0){//表示在父進程中,父進程寫
    //關閉管道讀描述符,進行管道寫操作
        close(pipe_fd[0]);
        if(write(pipe_fd[1],"Hello",5)!=-1)
            printf("parent write1 success!/n");
        if(write(pipe_fd[1],"Pipe",5)!=1)
            printf("parent write2 success!/n");
        close(pipe_fd[1]);
        sleep(3);
        waitpid(pid,NULL,0);
        exit(0);
    }
}
    
管道讀寫注意事項:
1.必須在系統調用fork()中調用pipe(),否則子進程將不會繼承檔案描述符;
2.當使用半雙工管道時,任何關聯的進程都必須共用一個相關的祖先進程。

 

轉載聲明: 本文轉自 http://hi.baidu.com/glowzrf/blog/item/2e3edd17ed23b8044b90a70e.html

======================================================================

 

擴充參考:

 

具名管道FIFO——Linux筆記

http://hi.baidu.com/glowzrf/blog/item/dcaf96fb28c941136d22eb9f.html

 

訊號——Linux學習筆記

http://hi.baidu.com/glowzrf/blog/item/2828d6ce8a17d63cb700c8e9.html

 

守護進程——Linux學習筆記

http://hi.baidu.com/glowzrf/blog/item/35fd44949629781bd31b70d7.html

 

共用記憶體——Linux學習筆記

http://hi.baidu.com/glowzrf/blog/item/9a2e97e7e9f1272bb938208d.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.