linux命名管道的使用
linux系统中管道有两种,一种是匿名管道,只能在有血缘关系的进程间使用。一种是命名管道。可以使用在没有血缘关系进程之间。比如两个程序,一个负责向管道写入数据,另外一个负责读出数据。
试验非常方便,
负责读的程序 fifo_r.c
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>int main() {int count = 0;const char *path = "./fifo_file";int fd = open(path, O_RDONLY); char buf[128]={0};for( count = 0; count < 10; count++){memset( buf, 0, sizeof(buf) );ssize_t n = read(fd, buf, sizeof(buf));printf("read:%s\n", buf); }close(fd);return 0;
}
负责写的程序 fifo_w.c.
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>int main() {int count = 0;const char *path = "./fifo_file";char *str = "hello world camel";mkfifo(path, 0666); int fd = open(path, O_WRONLY);for( count = 0; count < 10; count++){ write( fd, str, strlen(str) );usleep(50);}close(fd);return 0;
}
fifo_w.c向管道写入"hello world camel", fifo_r.c从管道读出"hello world camel",写入十次,读出十次。