1.進程間通信的目的:
1.數據傳輸 2.共享數據 3.通知事件 4.資源共享 5.進程控制
2.進程間通信的方法:
1.管道(Pipe)和有名管道(FIFO)
2.信號(Signal)
3.消息隊列
4.共享內存(Shared Memory)
5.信號量(Semaphore)
6.套接字(Socket)
(1)管道通信:管道是半雙工的,數據只能向一個方向流動,需要雙方通信時需要建立兩個管道。
只能用在具有親緣關係的進程之間(有名管道不受限制)。
單獨構成一種獨立的文件系統。
數據的寫入和讀出:一個進程向管道的一端寫入內容,被另一個進程在管道的另外一端讀出。寫入的內容每次都 添加在管道緩衝區的末尾,並且每次都是從緩衝區的頭部讀出數據。
pipe(); 函數用來建立無名管道。
下面是父子進程雙向通信的示例代碼,需要注意的是要創建兩個管道。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
int main()
{
pid_t pid;
int i;
int fd[2];
char buf[100];
//一定要在創建子進程之前創建管道,否則子進程也會創建不需要的管道。
if(pipe(fd) < 0)
{
printf("pipe error\n");
exit(0);
}
printf("fd[0] = %d, fd[1] = %d \n", fd[0], fd[1]);
pid = fork(); //創建子進程
if(pid < 0)
{
printf("FORK ERROR\n");
exit(1);
}
else if(pid > 0) //父進程
{
close (fd[0]); //關閉讀取端
char s[] = {"hello . . . \n"};
write(fd[1], s, sizeof(s));
sleep(1);
close (fd[1]); //關閉寫入端
wait(NULL);
}
else //子進程
{
close (fd[1]);
read(fd[0], buf, sizeof(buf));
printf("I am a child!\n");
printf("%s", buf);
close (fd[0]);
exit(0);
}
return 0;
}