[Linux] 利用 pipe 解決 fork 共用變數問題
圖片來源:https://jan.newmarch.name/ProgrammingUnix/ipc/lecture.html |
目錄
一.背景知識
二.實作步驟
三.參考文獻
一.背景知識
2.fork()
In computing, particularly in the context of the Unix operating system and its workalikes, fork 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
留言
張貼留言