无名管道:
Linux中 inode 用于唯一标识一个文件,而无名管道(pipe)在系统中是没有名字的,也就是没有(inode),它的内容直接保存在操作系统的内核中。
无名管道可以通过系统 API 提供的 IO 函数进行操作,但是不能使用 open/close 函数进行打开或者关闭。
无名管道使用 read/write 进行读写,但是 使用 read/write 必须得有一个文件描述符。所以,使用无名管道 pipe 时,就必须先创建 文件描述符。
文件描述符的创建:
#include <unistd.h>
int pipe(int pipefd[2]);
参数:
@pipefd[0]: 保存 read 文件描述符
@pipefd[1]: 保存 write 文件描述符
返回值:
成功返回 0
失败返回 -1,并设置错误码 errno
pipe 无名管道的特点:
1.pipe 有两端,一端用来读取数据,一端用来写入数据
2.按顺序读取,不能使用 lseek
3.内容读取完毕,管道中就没有数据了
4.pipe 随内核持续性
无名管道的操作流程
1.创建文件描述符
2.创建子进程
3.在子进程中写入数据
4.在父进程中读取数据
5.关闭无名管道
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#define N 30
int main()
{
// 1、先创建一个无名管道
int pipefd[2];
if(pipe(pipefd) == -1)
{
perror("pipe error");
exit(-1);
}
// 2、创建新进程进行通信 子进程写入管道数据,父进程读取
char buf[N] = { 0}; // 保存数据
if(fork() == 0) // 子进程
{
while(1)
{
scanf("%s",buf); // 不能获取空白字符
write(pipefd[1],buf,N);
if(strcmp(buf,"over") == 0) // 输入 over 结束
{
printf("CHILD OVER\n");
exit(0);
}
}
}
else
{
while(1)
{
read(pipefd[0],buf,N);
printf("CHILD SEND %s\n",buf);
if(strcmp(buf,"over") == 0) // 输入 over 结束
{
printf("PAPA OVER\n");
wait(NULL);
break;
}
}
}
// 3、关闭无名管道
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
&spm=1001.2101.3001.5002&articleId=136676490&d=1&t=3&u=847338e72dcf4078ac64dda03c878687)
581

被折叠的 条评论
为什么被折叠?



