文章目录
- 管道通信
- 无名管道
- 有名管道
管道通信
无名管道
无名管道只能在有亲缘关系之间的进程间通信(比如父子进程)。
- 第一步是创建一个管道,这个管道有两个文件描述符
- 一个读,一个写
- 两个文件描述符fd[2],一个文件描述符(fd[0]
)用来读,一个文件描述符(fd[1]
)用来写。
man命令查询:man 2 pip
PIPE(2) Linux Programmer's Manual PIPE(2)
NAME
pipe, pipe2 - create pipe
SYNOPSIS
#include <unistd.h>
int pipe(int pipefd[2]);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <fcntl.h> /* Obtain O_* constant definitions */
#include <unistd.h>
int pipe2(int pipefd[2], int flags);
DESCRIPTION
pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication. The array
pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of
the pipe. pipefd[1] refers to the write end of the pipe. Data written to the write end of the pipe is buffered by
the kernel until it is read from the read end of the pipe. For further details, see pipe(7).
代码验证:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int fd[2]; // read: fd[0], write: fd[1]
char buf[32] = {0};
pipe(fd);
printf("fd[0] is %d\n", fd[0]);
printf("fd[1] is %d\n", fd[1]);
pid = fork();
if(pid < 0)
{
printf("error \n");
}
if(pid > 0)
{
int status;
close(fd[0]);
write(fd[1], "hello", 5);
close(fd[1]);
wait(&status);
exit(0);
}
if(pid == 0)
{
close(fd[1]);
read(fd[0], buf, 32);
printf("buf is %s\n", buf);
close(fd[0]);
exit(0);
}
}
有名管道
有名管道可以实现没有任何关系之间的进程进行通信。
有名管道第一步不是创建管道,而是创建一个FIFO类型的特殊文件,使用的创建函数是:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
查看函数使用的命令是man 3 mkfifo