您的位置:首页 > 运维架构 > Linux

Linux进程入门学习(六)-管道通信

2017-08-20 10:09 471 查看

1. 无名管道

pipe 函数用于创建管道

头文件:
#include <unistd.h>


函数原型:
int pipe(int pipefd[2]);


返回值:

成功:0
失败:-1


参数列表:

int pipefd[2]:一个int 类型的数组,pipefd[0]读端,pipefd[1]写端

close 函数用于关闭管道

close(f[0]);

close(f[1]);

无名管道的特征:

1.没有名字,因此无法使用open( )。

2.只能用于亲缘进程间(比如父子进程、兄弟进程、祖孙进程……)通信。

3.半双工工作方式:读写端分开。

4.写入操作不具有原子性,因此只能用于一对一的简单通信情形。

5.不能使用lseek( )来定位。

6.无名管道不存在于普通磁盘,当进程退出后就会消失。

无名管道的操作步骤

1.创建一个无名管道– -相当于打开了两个文件,实质是打开了无名管道的两端

2.一个进程可以通过f[1]进行写操作

3.另外一个进程可以通过f[0]进行读操作

4.关闭无名管道

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char **argv)
{
int fd[2];

if(pipe(fd) == -1)
{
perror("pipe()");
exit(1);
}

pid_t x = fork();

if(x == 0)
{
char *s = "hello, I am your child\n";
write(fd[1], s, strlen(s));
}

if(x > 0)
{
char buf[30];
bzero(buf, 30);

read(fd[0], buf, 30);
printf("from child: %s", buf);
}

close(fd[0]);
close(fd[1]);
return 0;
}


运行结果:



2.有名管道

mkfifo 函数用于创建有名管道

头文件:

#include <sys/types.h>
#include <sys/stat.h>


函数原型:
int mkfifo(const char *pathname, mode_t mode);


返回值:

成功:0
失败:-1


参数列表:

const char *pathname:文件名路径
mode_t mode:文件权限


有名管道FIFO 的特征:

1,有名字,存储于普通文件系统之中。

2,任何具有相应权限的进程都可以使用open( )来获取FIFO 的文件描述符。

3,跟普通文件一样:使用统一的read( )/write( )来读写。

4,跟普通文件不同:不能使用lseek( )来定位,原因同PIPE。

5,具有写入原子性,支持多写者同时进行写操作而数据不会互相践踏。

6,First In First Out,最先被写入FIFO 的数据,最先被读出来。

示例代码:使用命名管道FIFO,实现两个进程间通信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息