linux系统编程-进程间通信-无名管道(pipe)
有名管道:
可以实现两个无关系的进程间通信。可以用于统一PC的不同进程之间的通信。
因为在文件系统中是可见的,也就是说可以用路径来指出,因此就是有名管道,也是用的一段内存进行通信,在通信结束后,内容被清空,因此这个文件在文件系统中永远是0,不能使用 seek lseek 。也会支持读阻塞 写阻塞,没有空间写阻塞。遵循先入先出。
有名管道使用步骤:
- 创建有名管道。不能用open,因为open只能创建普通文件,不能创建管道文件,在这里使用的mkfifio来创建管道文件,这个文件是专门用于进程间通信。
操作步骤:
- 打开文件:open
- 读写文件:write 、 read
- 关闭文件:close
yuupeng@ubuntu:~/test$ man mkfifo /*查看帮助*/
MKFIFO(1) User Commands MKFIFO(1)
NAME
mkfifo - make FIFOs (named pipes)
SYNOPSIS
mkfifo [OPTION]... NAME...
DESCRIPTION
Create named pipes (FIFOs) with the given NAMEs.
Mandatory arguments to long options are mandatory for short options
too.
例程
有名管道可以实现两个没有关系的进程间通信。在管道创建成功功后会在系统文件中看有一个真实的文件存在,因此叫有名管道。
写进程
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#define SIZE 100
int main(int argc,char *argv[]){
int fd=0;
int ret =0;
char buf[SIZE]={"fifo data\n"};
//创建管道
ret= mkfifo("FIFO",0666);
if(-1 == ret && EEXIST !=errno){
perror("FIFO error");
return -1;
}
//open管道
fd= open("FIFO",O_WRONLY);
if(fd <0){
perror("open fifo error");
return -1;
}
//在管道里写内容
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
读进程
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#define SIZE 100
int main(int argc,char *argv[]){
int fd=0;
int ret =0;
char buf[SIZE]={"0"};
//open管道
fd= open("FIFO",O_RDONLY);
if(fd <0){
perror("open fifo error");
return -1;
}
//读管道内容
read(fd,buf,SIZE-1);
//输出结果
printf("buf = %s\n",buf);
//关闭管道
close(fd);
return 0;
}
程序测试
第一个终端:
yuupeng@ubuntu:~/test$ gcc fifo_w.c -o w
yuupeng@ubuntu:~/test$ ./w /*执行写进程这里会阻塞,等待读进程将fifo中数据读出*/
yuupeng@ubuntu:~/test$
yuupeng@ubuntu:~/test$ gcc fifo_r.c -o r
yuupeng@ubuntu:~/test$ ls -al /* 查看当前文件夹下是否存在管道文件 */
total 48
drwxrwxr-x 2 yuupeng yuupeng 4096 May 22 06:00 .
drwxr-xr-x 30 yuupeng yuupeng 4096 May 22 05:49 ..
/*p:管道文件。fifo 真实的文件,因此不同进程就像操作文件一样将fifo中的内容读出,因此叫有名管道*/
prw-rw-r-- 1 yuupeng yuupeng 0 May 22 06:00 FIFO
-rw-rw-r-- 1 yuupeng yuupeng 485 May 22 05:59 fifo_r.c
-rw-rw-r-- 1 yuupeng yuupeng 583 May 22 05:59 fifo_w.c
-rwxrwxr-x 1 yuupeng yuupeng 8691 May 22 06:00 r
-rwxrwxr-x 1 yuupeng yuupeng 8806 May 22 06:00 w
yuupeng@ubuntu:~/test$ ./r /*执行读进程,并且写进程随着读进程读数据而退出阻塞状态*/
buf = fifo data /*写进程向管道文件中写的数据*/