进程间常见的通信方式之管道
1. 匿名管道pipe: 管道是一种半双工的通信方式,数据只能单向流动。一般会创建两个管道使其变为全双工,这个只能在具有亲缘关系的进程间使用,通常的父子进程之间。
举例:
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
"pipe.c" 48L, 1142C 31,43 33%
2. 有名管道FIFO:有名管道也是半双工的通信方式,但是它允许无亲缘关系的进程间通信。其实不管匿名管道与有名管道都是通过内核缓冲区实现的数据的传输,有名管道会在内核特殊的文件系统中建立一个文件,任何进程都可以打开它,当前进程结束时,这个文件还是存在的。当然重启之后就没有了,因为是在内存中
举例:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int rfd,wfd;
fd_set rd_set;
struct timeval timeout;
char str[64] = "";
mkfifo("fifo1", 0777);
// open pipe file mode: 1. O_RDWR Mode; 2. make O_NONOBLOCK mode to O_RDONLY & O_WRONLY open file.
rfd = open("fifo1",O_RDONLY |O_NONBLOCK); // read pipe point
if(rfd < 0)
{
perror("open fifo1 pipe file is failed!\n");
return -1;
}
wfd = open("fifo1", O_WRONLY | O_NONBLOCK); //write pipe point
if(wfd < 0)
{
perror("open fifo2 pipe file is failed!\n");
return -1;
}
"mkfifo.c" 67L, 1247C 16,23-30 顶端