管道的認(rèn)識(shí)從command1 | command2 認(rèn)識(shí)開(kāi)始,到現(xiàn)在做A2DP升華,寫(xiě)一些使用FIFO的要點(diǎn)下來(lái)。
1 管道一般用于進(jìn)程間通信,把一個(gè)進(jìn)程的輸出通過(guò)管道送給另一個(gè)進(jìn)程。
2 可以通過(guò)popen,pclose嘗試實(shí)現(xiàn)command1 | command2 。
File *popen(const char * command, const char *open_mode);
open_mode: r or w
File a =popen("uname -a", "r");
fread(buffer, 1, BUFSIZE, a);
printf("%s", buffer);
>> Linux Ubuntu 8.09..................
3 pipe創(chuàng)建管道
#include <unistd.h>
int pipe(int file_description[2]);
pipe的參數(shù)是由兩個(gè)文件描述符組成的數(shù)組。file_description[0] 用于讀管道, file_description[1] 用來(lái)寫(xiě)管道。
4 命名管道:mkfifo
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char * filename, mode_t mode);
mode: O_RDONLY, O_WRONLY, O_NONBLOCK.
共四種組合:
O_RDONLY:阻塞讀方式打開(kāi),除非有進(jìn)程以寫(xiě)方式打開(kāi),不然阻塞。
O_RDONLY|O_NONBLOCK: 不論怎樣,立即返回,總是成功
O_WRONLY: 阻塞寫(xiě)方式打開(kāi),直到有人來(lái)讀,不然阻塞
O_WRONLY|O_NONBLOCK: 立即返回,但如果沒(méi)人以讀方式打開(kāi),返回-1錯(cuò)誤
FIFO SIZE:#include <limites.h>, PIPE_BUF, default 4096
多個(gè)進(jìn)程可以寫(xiě)同一個(gè)管道。