Linux系統編程@進程通訊(一)

來源:互聯網
上載者:User

標籤:

處理序間通訊概述

需要進程通訊的原因:

資料轉送

資源共用

 

通知事件

進程式控制制

Linux處理序間通訊(IPC)發展由來

Unix處理序間通訊

基於System V處理序間通訊(System V:UNIX系統的一個分支)

POSIX處理序間通訊(POSIX:可移植作業系統介面,為了提高UNIX環境下應用程式的可移植性。很多其他系統也支援POSIX標準(如:DEC OpenVMS和Windows)。)

 

現在Linux使用的處理序間通訊方式包括:

管道(pipe)、有名管道(FIFO)

訊號(signal)

訊息佇列

共用記憶體

訊號量

通訊端(socket)

 

管道通訊

 

管道:單向的、先進先出的,把一個進程的輸出和另一個進程的輸入串連起來。一個進程(寫進程)在管道尾部寫入資料,另一個進程(讀進程)從管道的頭部讀出資料。包括無名管道和有名管道,無名管道只用於父進程和子進程間的通訊,有名管道可用於運行同一系統中的任意兩個進程間的通訊。

管道的建立

無名管道建立

int pipe(int filedis[2]);   

int pipe_fd[2];
if(pipe(pipe_fd)<0){printf("pipe create error\n");return -1;}

當一個管道建立時,他會建立兩個檔案描述符,filedis[0]用於讀管道,filedis[1]用於寫管道。

管道的關閉

int close(); //使用close分別關閉兩個檔案描述符

當管道的一端被關閉後,下面兩條規則起作用

1.當讀(read)一個寫端已被關閉的管道時,在所有資料都被讀取後,read返回0,表示檔案結束。

使用無名管道通訊執行個體

通常,進程會先調用pipe,接著調用fork(這兩步為了確保只產生一個管道,且子進程產生後能夠繼承檔案描述符),從而建立從父進程到子進程的IPC管道。

 1 #include <unistd.h> 2 #include <string.h> 3 #include <sys/types.h> 4 #include <errno.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7  8 int main() 9 {10     int pipe_fd[2];11     pid_t pid;12     char buf_r[100];13     char* p_wbuf;14     int r_num;15     16     memset(buf_r,0,sizeof(buf_r));17     18     /*建立管道*/19     if(pipe(pipe_fd)<0)20     {21         printf("pipe create error\n");22         return -1;23     }24     25     /*建立子進程*/26     if((pid=fork())==0)  //子進程 27     {28         printf("\n");29         close(pipe_fd[1]);    //寫關閉30         sleep(2); /*為什麼要睡眠*/31         if((r_num=read(pipe_fd[0],buf_r,100))>0)32         {33             printf(   "%d numbers read from the pipe is %s\n",r_num,buf_r);34         }    35         close(pipe_fd[0]);36         exit(0);37       }38     else if(pid>0)        //父進程39     {40         close(pipe_fd[0]);  //讀關閉41         if(write(pipe_fd[1],"Hello",5)!=-1)42             printf("parent write1 Hello!\n");43         if(write(pipe_fd[1]," Pipe",5)!=-1)44             printf("parent write2 Pipe!\n");45         close(pipe_fd[1]);46         sleep(3);47         waitpid(pid,NULL,0); /*等待子進程結束*/48         exit(0);49     }50     return 0;51 }
View Code

 

 

訊號通訊

 

 

 

共用記憶體

 

 

 

 

訊息佇列

 

 

 

 

訊號量

 

Linux系統編程@進程通訊(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.