管道
进程间通信2:管道
管道命令:|,
root@student-machine:~# ls -l | grep ^d | wc -l 统计当前目录下的子目录个数
10
管道有方向:管道左边命令的输出作管道右边命令的输入
管道的特征:
1.管道是半双工
2.无名管道只能用于有亲缘关系的进程,命名管道用于非亲缘关系的进程
3.数据的读出和写入必须同步, 关闭读端去写会导致进程异常结束, 关闭写端去读会使用read()非阻塞读不到数据
4.管道不能使用lseek();
无名管道:
1.创建无名管道
int pipe(int pipefd[2]);
@pipefd:描述符数组: pfd[0]:只能作读端(read()), pfd[1]:只能作写端(write());
2.一个进程write()发数据,一个进程read()收数据,同步
3.关闭close();
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
//创建无名管道
int pfds[2] = {0};//初始化读写端
if(pipe(pfds) < 0)//创建管道
{
printf("pipe error\n");
return -1;
}
printf("pfds[0] = %d,pfds[1] = %d\n",pfds[0],pfds[1]);
//向无名管道写入文件
const char *data = "hello world";
int len = write(pfds[1],data,strlen(data));
//向无名管道读取文件
char buf[128] = "";
len = read(pfds[0],buf,sizeof(buf) - 1);
printf("pfds[0] recv data len = %d,buf = %s\n",len,buf);
close(pfds[0]);
close(pfds[1]);
}