无名管道
无名管道是最古老的进程通信方式, 有如下两个特点:
1. 只能用于有关联的进程间数据交互, 如父子进程, 兄弟进程, 子孙进程, 在目录中看不到文件节点, 读写文件描述符存在一个 int 型数组中。
2. 只能单向传输数据, 即管道创建好后, 一个进程只能进行读操作, 另一个进程只能进行写操作,读出来字节顺序和写入的顺序一样。
函数 | int pipe(int pipefd[2]) |
头文件 | #include <unistd.h> |
参数 pipefd[2] | 一个 int 型数组, 表示管道的文件描述符, pipefd[0]为读, pipefd[1]为写, 如下图 所示: |
返回值 | 成功返回 0, 失败返回-1 |
功能 | 创建无名管道 |
无名管道使用步骤:
1. 调用 pipe()创建无名管道;
2.fork()创建子进程,一个进程读,用read(),一个进程写,用write()。
实验代码
实现子进程和父进程之间的通信, 创建无名管道, 父进程从终端获取数据, 写入管道, 子进程从管道读数据并打印出来。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(void)
{
char buf[32] = {0};
pid_t pid;
// 定义一个变量来保存文件描述符
// 因为一个读端, 一个写端, 所以数量为 2 个
int fd[2];
// 创建无名管道
pipe(fd);
printf("fd[0] is %d\n", fd[0]);
printf("fd[2] 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);
}
return 0;
}
在 Ubuntu 上编译运行, 如下图所示:
有名管道
有名管道中可以很好地解决在无关进程间数据交换的要求, 并且由于它们是存在于文件系统中的, 这也提供了一种比匿名管道更持久稳定的通信办法。 有名管道在一些专业书籍中叫做命名管道, 它的特点是
1.可以使无关联的进程通过 fifo 文件描述符进行数据传递;
2.单向传输有一个写入端和一个读出端, 操作方式和无名管道相同。
我们使用 mkfifo()函数创建有名管道。 函数详解如下所示:
函数 | int mkfifo(const char *pathname, mode_t mode) |
头文件 | #include <sys/types.h> #include <sys/stat.h> |
参数 pathname | 有名管道的路径和名称 |
参数 mode | 权限 |
返回值 | 成功返回 0, 失败返回-1 |
有名管道使用步骤:
1. 使用 mkfifo()创建 fifo 文件描述符。
2. 打开管道文件描述符。
3. 通过读写文件描述符进行单向数据传输。
使用命令创建管道文件
输入以下命令创建管道文件, 并查看, 如下图所示:
mkfifo fifo
ls
ls -al
实验代码
创建两个无关联的进程, 一个进程创建有名管道并写数据, 另一个进程通过管道读数据。
fifo_write.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int ret;
char buf[32] = {0};
int fd;
if (argc < 2)
{
printf("Usage:%s <fifo name> \n", argv[0]);
return -1;
}
if (access(argv[1], F_OK) == -1)
{
ret = mkfifo(argv[1], 0666);
if (ret == -1)
{
printf("mkfifo is error \n");
return -2;
}
printf("mkfifo is ok \n");
}
fd = open(argv[1], O_WRONLY);
while (1)
{
sleep(1);
write(fd, "hello", 5);
}
close(fd);
return 0;
}
fifo_read.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buf[32] = {0};
int fd;
if (argc < 2)
{
printf("Usage:%s <fifo name> \n", argv[0]);
return -1;
}
fd = open(argv[1], O_RDONLY);
while (1)
{
sleep(1);
read(fd, buf, 32);
printf("buf is %s\n", buf);
memset(buf, 0, sizeof(buf));
}
close(fd);
return 0;
}
在Ubuntu 下编译 fifo_read.c, 并运行如下图所示:
然后重新打开一个窗口, 编译 fifo_write.c 并运行如下图所示:
fiforead 进程可以看到从管道读出的数据: