IPC(Inter-Process Communication)為什麼必要?因為每個進程都有各自的使用者位址空間,一個進程的全域變數在另一個進程裡完全看不到。要交換資料就必須經過核心:核心開一塊緩衝區,進程一把資料從使用者空間拷進核心緩衝區,進程二再從核心緩衝區讀走。這套機制就是進程間通信。
1. 管道與命名管道:管道可用於有親緣關係的進程;命名管道(named pipe)克服了沒有名字的限制,允許無親緣關係的進程溝通。
2. 信號(Signal):較複雜的通信方式,用於通知接收進程某事件發生,進程也能對自己送訊號。Linux 除了支援早期 signal 語義,也支援符合 POSIX.1 的 sigaction。
3. 訊息佇列:訊息的連結串列,分 POSIX 與 System V 兩種。克服了信號承載資訊量少、管道只能傳無格式位元組流且緩衝區大小受限等缺點。
4. 共享記憶體:多個進程存取同一塊記憶體,是最快的 IPC 形式,常與信號量搭配以完成同步與互斥。
5. 信號量(semaphore):主要作為進程間以及同一進程不同線程間的同步手段。
6. Socket:更通用的機制,可用於不同機器之間的進程通信。
#include <unistd.h> int pipe(int filedes[2]);
呼叫 pipe 時核心會開一塊緩衝區(即管道),它有讀端與寫端,透過 filedes 傳回兩個檔案描述符:filedes[0] 是讀端,filedes[1] 是寫端(好記的方式是對照 0 為標準輸入、1 為標準輸出)。在使用者程式眼中,管道就像一個開啟的檔案,read/write 其實是在讀寫核心緩衝區。成功回傳 0,失敗回傳 -1。
建立管道通信的三步:
1. 父進程呼叫 pipe,取得兩個描述符;
2. 父進程 fork 出子進程,子進程同樣持有這兩個描述符;
3. 父進程關閉讀端、子進程關閉寫端,於是父寫子讀。管道以環形佇列實作,資料從寫端流入、讀端流出。
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
{
int _pipe[2];
if (pipe(_pipe) == -1) {
printf("creat pipe error! errno code is:%d\n", errno);
return 1;
}
pid_t id = fork();
if (id < 0) {
printf("fork error!");
return 2;
} else if (id == 0) { /* child */
close(_pipe[0]);
int i = 0;
char *_mesg_c = NULL;
while (i < 100) {
_mesg_c = "i im coder";
write(_pipe[1], _mesg_c, strlen(_mesg_c) + 1);
sleep(1);
i++;
}
} else { /* father */
close(_pipe[1]);
char _mesg[100];
int j = 0;
while (j < 100) {
memset(_mesg, '\0', sizeof(_mesg));
read(_pipe[0], _mesg, sizeof(_mesg));
printf("%s\n", _mesg);
j++;
}
}
return 0;
}

兩個進程透過一個管道只能單向通信,要雙向就得再開一條。管道的讀寫端靠開啟的檔案描述符傳遞,因此通信雙方必須從共同祖先繼承到描述符——可以是父子之間,也可以父進程 fork 兩次把描述符交給兩個子進程。一句話:使用管道的進程之間必須有親緣關係。
1. 寫端全部關閉(引用計數為 0),讀端仍要讀:剩餘資料讀完後,再次 read 會回傳 0,就像讀到檔案末尾。只要把子進程的寫入迴圈改小並在結束時 close 寫端即可觀察:
else if (id == 0) { /* child */
close(_pipe[0]);
int i = 0;
char *_mesg_c = NULL;
while (i < 10) {
_mesg_c = "i im coder";
write(_pipe[1], _mesg_c, strlen(_mesg_c) + 1);
sleep(1);
i++;
}
close(_pipe[1]);
}

2. 寫端未關閉(引用計數大於 0)但沒有資料寫入:讀端把剩餘資料讀完後,read 會阻塞,直到管道裡有資料可讀才返回。
3. 讀端全部關閉,仍有進程寫入:該進程會收到 SIGPIPE,通常導致異常終止。
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
void fun() { printf("zhongzhi\n"); }
int main()
{
signal(SIGPIPE, fun); /* 自訂 SIGPIPE 處理,避免直接終止 */
int _pipe[2];
if (pipe(_pipe) == -1) {
printf("create pipe error! errno code is : %d\n", errno);
return 1;
}
pid_t id = fork();
if (id < 0) {
printf("fork error!");
return 2;
} else if (id == 0) { /* child */
close(_pipe[0]);
int i = 0;
char *_mesg_c = NULL;
while (i < 20) {
if (i < 10) {
_mesg_c = "i am child!";
write(_pipe[1], _mesg_c, strlen(_mesg_c) + 1);
}
sleep(1);
i++;
}
} else { /* father */
close(_pipe[1]);
char _mesg[100];
int j = 0;
while (j < 3) {
memset(_mesg, '\0', sizeof(_mesg));
int ret = read(_pipe[0], _mesg, sizeof(_mesg));
printf("%s : code is : %d\n", _mesg, ret);
j++;
}
close(_pipe[0]); /* 關閉讀端後,子進程再寫就會觸發 SIGPIPE */
sleep(10);
if (waitpid(id, NULL, 0) < 0) return 3;
}
return 0;
}

4. 若把管道寫端設為非阻塞,寫入時核心緩衝區已滿會回傳錯誤並設定 errno 為 EAGAIN,而不是阻塞等待。
#include <sys/types.h> #include <sys/stat.h> int mknod(const char *path, mode_t mod, dev_t dev); int mkfifo(const char *path, mode_t mode);
path 是完整路徑;mode 指定存取權限;dev 為裝置值,只在建立裝置檔時才用到。兩個函式成功回傳 0,失敗回傳 -1。
umask(0);
if (mknod("/tmp/fifo", S_IFIFO | 0666) == -1) {
perror("mkfifo error");
exit(1);
}
umask(0);
if (mkfifo("/tmp/fifo", S_IFIFO | 0666) == -1) {
perror("mkfifo error!");
exit(1);
}
S_IFIFO | 0666 表示建立一個權限 0666 的命名管道,即擁有者、同群組與其他使用者都可讀可寫(別忘了 umask 會影響最終權限)。命名管道建立後用法與匿名管道幾乎相同,差別在於使用前必須先 open()——因為它是存在硬碟上的檔案,而匿名管道存在記憶體中。
要注意 open() 可能被阻塞:以 O_RDWR 開啟不會阻塞;以 O_RDONLY 開啟會等到有寫方開啟才返回;以 O_WRONLY 開啟則會等到有讀方開啟。
總結:mkfifo 在檔案系統中建立一個提供 FIFO 功能的檔案。此前提到的管道都沒有名字,故稱匿名管道,對檔案系統不可見,只能用在父子進程之間;命名管道則是看得見的檔案,任何兩個進程都能用它通信,不必有親緣關係。
以下以伺服器端與客戶端一組程式演示 FIFO:
/* FIFO server 端 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define _PATH_ "./file.tmp"
#define _SIZE_ 100
int main()
{
int ret = mkfifo(_PATH_, 0666 | S_IFIFO);
printf("%d\n", ret);
if (ret == -1) { printf("mkfifo error\n"); return 1; }
int fd = open(_PATH_, O_WRONLY);
if (fd < 0) { printf("open file error!\n"); return 1; }
char buf[_SIZE_];
memset(buf, '\0', sizeof(buf));
while (1) {
scanf("%s", buf);
if (write(fd, buf, sizeof(buf)) <= 0) {
printf("write end or error!\n");
break;
}
printf("%s\n", buf);
if (strncmp(buf, "quit", 4) == 0) break;
}
close(fd);
return 0;
}
/* FIFO client 端 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define _PATH_ "./file.tmp"
#define _SIZE_ 100
int main()
{
int fd = open(_PATH_, O_RDONLY);
if (fd < 0) { printf("open file error!\n"); return 1; }
char buf[_SIZE_];
memset(buf, '\0', sizeof(buf));
while (1) {
int ret = read(fd, buf, sizeof(buf));
if (ret <= 0) { printf("read end or error!\n"); break; }
printf("%s\n", buf);
if (strncmp(buf, "quit", 4) == 0) break;
}
close(fd);
return 0;
}

實務上通常先啟動讀取端再啟動寫入端,這樣可避免 open() 階段互相等待而卡住。