先说一下有名管道和无名管道用的函数:函数
无名管道使用的是 pipe()spa
有名管道使用的是fifo()code
无名管道主要用于有血缘关系的两个进程间通讯,是内核使用环形队列机制实现,借助内核缓冲区实现的。blog
有名管道主要用于两个不相干的进程间通讯,我认为之因此叫有名管道是由于他们借助mkfifo()函数建立的伪文件利用内核缓冲区进行通讯,由于建立文件能够指定文件名因此操做和使用文件几乎同样。队列
首先关于无名管道 pipe()函数 须要指定两个文件描述符,经过pipe()函数建立一个管道使其一端读文件一端写进程
1 int fd[2]; 2 pipe(fd);
其中默认 fd[0]读文件,fd[1]写文件。ip
#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main(void) { int fd[2]; int ret = pipe(fd); if (ret == -1) { perror("pipe error!"); exit(-1); } pid_t pid = fork(); if (pid == -1) { perror("fork error!"); exit(-1); } else if (pid == 0)//子进程读数据 { close(fd[1]); char buf[1024]; ret = read(fd[0], buf, sizeof(buf)); if (ret == 0) printf("------\n"); write(STDOUT_FILENO, buf, ret); } else { close(fd[0]);// 父进程写数据 char* str = "Hello pipe\n"; write(fd[1], str, strlen(str)); sleep(2); } }
而fifo()函数是一个进程写数据,一个进程读数据,两个进程不能结束内存
一端读数据string
#include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> int main(void) { int fd = open("abc", O_RDONLY); char buf[1024]; while (1) { sleep(1); int ret = read(fd, buf, sizeof(buf)); if (ret == -1) { perror("read error"); exit(-1); } if (ret != 0) //若是ret == 0 那么内存缓冲区就是空的 printf("%s\n", buf); } close(fd); return 0; }
一个进程写数据it
#include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> int main(void) { int ret = access("abc", F_OK); int fd; if (ret != 0) { ret = mkfifo("abc", 0777); if (ret == -1) //若是返回值是-1说明文件不存在 咱们就建立一个文件 { perror("mkfifo"); exit(-1); } } fd = open("abc", O_WRONLY); while(1) { sleep(1); char *str = "myname"; write(fd, str, sizeof(str)); } close(fd); return 0; }