程序間的通訊 一

2021-10-08 22:34:50 字數 1291 閱讀 2304

這一章節我們主要講程序間的通訊,主要方式大概有管道、訊號量、訊息列隊、共享記憶體等。

首先講管道,管道分為有名管道、無名管道。其中有名管道是用於父程序和子程序之間的通訊,太過於侷限。有名管道強大一些,可用於不相關 的程序之間的通訊。

#include

#include

#include

#include

#include

intmain

(int argc,

char

*ar**)

cpid=

fork()

;if(cpid==-1

)if(cpid==0)

else

}

這裡編寫兩個程式 進行通訊

//讀

#include

#include

#include

#include

#include

#define fifo "/tmp/myfifo"

intmain

(int argc,

char

*ar**)

memset

(buf,0,

sizeof

(buf));

fd=open

(fifo,o_rdonly|o_nonblock,0)

;if(fd==-1

)while(1

)else

}pause()

;ulink

(fifo)

;}

//寫

#include

#include

#include

#include

#include

#include

#include

#define fifo "/tmp/myfifo"

/* 使用帶參的 main 函式是因為要使用者輸入要寫入的內容 */

intmain

(int argc,

char

**ar**)

if(argc==1)

/* 將使用者輸入的資料先拷貝到 buf_w 緩衝區中 */

strcpy

(buf_w,ar**[1]

);/* 向管道中寫入字串 */if(

(nwrite=

write

(fd,buf_w,

100))==

-1)else

}

程序間通訊(二)

程序間通訊(一)

為什麼程序間要通訊?1 資料傳輸 2 資源共享 3 通知事件 4 程序控制 程序間通訊方式 管道通訊 共享記憶體 訊息佇列 訊號通訊 一 管道通訊 管道是單向的 先進先出的,它把乙個程序的輸出和另乙個程序的輸入連線在一起。乙個程序 寫程序 在管道尾部寫入資料,另乙個程序 讀程序 從管道的頭部讀出資料...

程序間通訊(一)

半雙工管道 fifo 全雙工管道 命名全雙工管道 訊息佇列 訊號量 共享記憶體 套接字 多機其它為單機 管道 包括無名管道 命名管道 訊息佇列 訊號量共享儲存 scoket streams 等。其中,scoket和stream支援不同主機上的兩個程序ipc。一 管道 管道,通常指無名管道,是unix...

程序間通訊 一)

測試 例子 從鍵盤讀取資料,寫入管道,讀取管道,寫到螢幕 include include include include intmain void memset buf,0x00 sizeof buf read from pipeif len read fds 0 buf,100 1 write t...