進程的地址空間是互相獨立的,因此進程之間交互數據必須採用專門的通信機制。尤其是在大型的軟件系統中,往往需要多個進程互相協作共同完成一個任務,這就需要使用進程間通信(Inter-Process Connection, IPC)編程技術。
管道(Pipe)是兩個進程之間進行單向通信的機制,因爲它的單向性,所以又稱爲半雙工管道。它主要用於進程間的一些簡單通信。
- 數據只能由一個進程流向另一個進程(一個寫管道,一個讀管道);如果要進行全雙工通信,需要建立兩個管道。
- 管道只能用於父子進程或者兄弟進程之間的通信。
- 管道沒有名字,且其緩衝區大小有限。
- 一個進程向管道寫數據,數據每次都添加在管道緩衝區的末尾;另一個進程從管道另一端讀數據,從緩衝區頭部讀出數據。
#include <unistd.h>
int pipe(int fd[2])
管道兩端分別用描述符fd[0]和fd[1]來描述。其中fd[0]只能用於讀,稱爲管道讀端;fd[1]只能用於寫,稱爲管道寫端。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
/*讀管道*/
void read_from_pipe (int fd)
{
char message[100];
read (fd,message,100);
printf("read from pipe:%s",message);
}
/*寫管道*/
void write_to_pipe (int fd)
{
char *message = "Hello, pipe!\n";
write (fd, message,strlen(message)+1);
}
int main(void)
{
int fd[2];
pid_t pid;
int stat_val;
if (pipe (fd))
{
printf ("create pipe failed!\n");
exit (1);
}
pid = fork();
switch (pid)
{
case -1:
printf ("fork error!\n");
exit (1);
case 0:
/*子進程關閉fd1*/
close (fd[1]);
read_from_pipe (fd[0]);
exit (0);
default:
/*父進程關閉fd0*/
close (fd[0]);
write_to_pipe (fd[1]);
wait (&stat_val);
exit (0);
}
return 0;
}
運行結果:
管道是半雙工的(一端只能讀不能寫,另一端只能寫不能讀)。如果想要實現兩個進程之間的全雙工通信,那可以創建2個這樣的管道來實現。具體的實現代碼在此就省略了。