Linux中进程间通信之管道
程序员文章站
2024-03-23 21:18:34
...
进程间通信:管道
管道:1、有名管道
2、无名管道
为什么要引入管道呢?
答:因为普通文件存储在磁盘中,读写效率低
管道文件存储在内存中,读写效率高
1、有名管道
(1)创建:mkfifo fifo
(2)open时需要两个进程(r读、w写)一起操作
(3)有名管道可以在任意两个进程间使用
(4)管道有读端和写端之分,当写端关闭之后,读端read就会返回0;
读端关闭后,写端写入数据就会引起异常,产生信号:SIGPIPE。
代码示例:
写端write.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <signal.h>
int main()
{
int fd = open("fifo",O_WRONLY);
assert(fd != -1);
printf("fd = %d\n",fd);
while(1)
{
char buff[128] = {0};
fgets(buff,128,stdin);
if(strncmp(buff,"end",3) == 0)
{
break;
}
write(fd,buff,128);
}
close(fd);
exit(0);
}
读端read.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd = open("fifo",O_RDONLY);
assert(fd != -1);
printf("fd = %d\n",fd);
while(1)
{
char buff[128] = {0};
int n = read(fd,buff,127);
//read(fd,buff,127);
if(n == 0)
{
break;
}
printf("read(n=%d): %s",n,buff);
}
close(fd);
exit(0);
}
代码执行:
解析:打开两个终端(进程),一个运行write,另一个运行read才能执行,在写端写入数据之后读端read就可以读到,当写入end后,写端关闭,读端也随之关闭。
2、无名管道
(1)创建:int pipe(int fd[2])
(2)fd[0]固定的读端
fd[1]固定的写端
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd[2];
pipe(fd);
pid_t pid = fork();
assert(pid != -1);
if(pid ==0)
{
close(fd[1]);
char buff[128] = {0};
read(fd[0],buff,127);
printf("buff = %s\n",buff);
}
else
{
close(fd[0]);
char buff[128] = {0};
fgets(buff,128,stdin);
write(fd[1],buff,strlen(buff));
close(fd[1]);
}
}
运行结果:
解析:当写入hello之后 ,buff就会读到hello
上一篇: Linux中进程间通信——消息队列
下一篇: 最新面试问题
推荐阅读
-
Linux中进程间通信——消息队列
-
Linux中进程间通信之管道
-
Linux编程基础之进程间通信之四:共享内存
-
进程间通信- - -管道
-
Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路
-
Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析
-
Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析
-
Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析
-
Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路
-
Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析