[Linux] 利用 pipe 解決 fork 共用變數問題

圖片來源:https://jan.newmarch.name/ProgrammingUnix/ipc/lecture.html

目錄

一.背景知識
二.實作步驟
三.參考文獻

一.背景知識
1.Linux
    Linux是一種自由和開放原始碼的類UNIX作業系統。術語Linux只表示作業系統核心本身,但通常採用Linux核心來表達該意思。Linux則常用來指基於Linux核心的完整作業系統,包括GUI元件和許多其他實用工具。由於這些支援使用者空間的系統工具和庫主要由理察·斯托曼於1983年發起的GNU計劃提供,自由軟體基金會提議將該組合系統命名為GNU/Linux[7][8],但Linux不屬於GNU計劃。

2.fork()
    In computing, particularly in the context of the Unix operating system and its workalikesfork is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel. Fork is the primary (and historically, only) method of process creation on Unix-like operating systems.

3.pipe
    pipe() creates a pipe, a unidirectional data channel that can be used for interprocess ommunication.  The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of the pipe.  pipefd[1] refers to the write end of the pipe.  Data written to the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe.

二.實作步驟

你會需要創立 pipe 的 file descriptor
int fd[2]
fd[0] 為讀取資料
fd[1]  為寫入資料
pipe(fd) 呼叫pipe作使用

接著再傳送端撰寫以下 code

close(fd[0]) // 傳送端沒有要接收資料, 故關閉讀取
write(fd[1], %value, sizeof(value)) // 參數為fd的寫入端, 傳送資料的buffer, 傳送資料的大小
close(fd[1]) // 寫完之後關閉

接收端則相反

close(fd[1]) // 接收端沒有要接收資料, 故關閉接收
read(fd[0], %value, sizeof(value)) // 參數為fd的傳送端, 接收資料的buffer, 接收資料的大小
close(fd[0]) // 接收結束之後關閉

以下為範例程式


http://i.imgur.com/xQ46SHP.png

執行結果
http://i.imgur.com/6SjI0Xx.png
若要看得更仔細的話, 可以看參考文獻中的連結

三.參考文獻
1.http://hwchiu.logdown.com/posts/1733-c-pipe
2.http://www.tldp.org/LDP/lpg/node11.html
3.https://itspg.wordpress.com/2011/11/08/linuxcpipenote/
4.http://myblog-maurice.blogspot.tw/2011/12/linux_15.html
5.https://jan.newmarch.name/ProgrammingUnix/ipc/lecture.html
6.man page

留言

這個網誌中的熱門文章

Raspberry pi 樹莓派系列 :安裝瀏覽器

『如何說出好故事|故事架構介紹|輕鬆做出大師級故事架構』

『目標管理|SMART原則|最有效的目標管理原則』