man 7 PIPE
pipe和FIFO介紹
pipe匿名管道肋联,只能用于有親緣關(guān)系的進(jìn)程間通信
FIFO命名管道瑟啃,任意兩個進(jìn)程間通信
匿名管道
pipe
? 創(chuàng)建匿名管道先蒋,用于進(jìn)程間通信,必須湊齊讀寫雙方
函數(shù)聲明
#include <unistd.h>
int pipe(int pipefd[2]);
參數(shù)含義
需要一個大小為2的整型一維數(shù)組首地址辩撑,回填兩個文件描述符界斜,pipefd[0]為讀端,pipefd[1]為寫端合冀。
返回值
成功返回0失敗-1
讀管道
用read(2)讀pipe(2)回填的讀端文件描述符
寫管道
用write(2)寫pipe(2)回填的寫端文件描述符
關(guān)閉管道
用close(2)關(guān)閉讀寫端兩個文件描述符
注意:
lseek(2) 不能作用于管道
uname -r 查看內(nèi)核版本
fcntl(2)可以用于設(shè)置管道容量各薇,管道默認(rèn)容量為4k
代碼示例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFSIZE 1024
int main(void)
{
pid_t pid;
int pfd[2];
char buf[BUFSIZE] = {};
if (pipe(pfd) == -1)
{
perror("pipe()");
exit(1);
}
pid = fork();
if (pid == -1)
{
perror("fork()");
goto ERROR;
}
if (pid == 0)
{
close(pfd[0]);
write(pfd[1], "hello", 5);
close(pfd[1]);
exit(0);
}
close(pfd[1]);
read(pfd[0], buf, BUFSIZE);
puts(buf);
close(pfd[0]);
wait(NULL);
exit(0);
ERROR:
close(pfd[0]);
close(pfd[1]);
exit(1);
}
命名管道
存在的系統(tǒng)文件
在終端用mkfifo(1)命令創(chuàng)建
在程序中用mkfifo(3)函數(shù)創(chuàng)建
如圖所示
命名管道的創(chuàng)建