linux 进程间通信 pipe
来源:互联网 发布:转录组数据上传 编辑:程序博客网 时间:2024/05/30 21:58
pipe 是有亲属关系的进程之间通信的经典方法
int pipe(int fd[2]); //创建管道的函数 成功返回0 出错返回-1
参数fd[2] 作为返回文件描述符的容器 fd[0]为读打开 fd[1]为写打开
可以fork子进程 继承文件描述符实现通信 可以fork多个子进程进行通信但是你要有足够的精力管理他们以至于 不会发生混乱所以这样做是不可取的
fpathconf和fpathconf可以确定管道的size
非阻塞管道, fcntl函数设置O_NONBLOCK标志
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
void err(char *name, int err_num)
{
perror(name);
exit(err_num);
return ;
}
int main()
{
int fd[2];
int pid;
char buf[1024];
if(pipe(fd) < 0)
{
err("pipe", -2);
}
int pipe_size = fpathconf(fd[1], _PC_PIPE_BUF);
printf("size of pipe : %d\n", pipe_size);
pid = fork();
if(pid < 0)
{
err("fork", -1);
}
else if(pid > 0)
{
close(fd[0]);
if(write(fd[1],"hello\n", strlen("hello\n")) < 0)
{
err("write", -2);
}
close(fd[1]);
waitpid(pid ,0,0);
}
else if(pid == 0)
{
int re;
sleep(1);
if((re = read(fd[0],buf, 1024)) < 0)
{
err("read", -3);
}
write(STDOUT_FILENO,buf, strlen(buf));
write(STDOUT_FILENO,"\n", strlen("\n"));
}
return 0;
}
四种特殊情况
1> 读端关闭 写管道 发出SIGPIPE信号 若忽略该信号或捕捉该信号并未从其处理程序返回 write返回-1 errno设置为EPIPE
2> 写端关闭 读管道 如果有数据则会把数据读出来 如果没有数据则相当于读空管道
3> 读空管道 阻塞 非阻塞返回 -1
4> 写满管道 阻塞 非阻塞返回-1
- linux 进程间通信 pipe
- Linux下的进程间通信PIPE
- Linux进程间通信之管道(pipe)
- Linux环境进程间通信 --- 管道Pipe
- Linux 进程间管道pipe通信
- LINUX进程间通信:PIPE与FIFO
- linux系统编程:进程间通信-pipe
- LINUX进程间通信:PIPE与FIFO
- Linux进程间通过pipe通信
- Linux进程间通信之管道(pipe)
- Linux进程间通信之管道(pipe)
- 进程间通信 之 pipe(Linux)
- 进程间pipe通信
- linux进程通信之pipe
- Linux--进程间通信(一)-管道(pipe)通信
- 进程间通信-管道pipe
- 进程间通信IPC --pipe
- 进程间通信 管道pipe
- 冒泡/下沉排序
- mahout in Action2.2-聚类介绍-K-means聚类算法
- 相对分子质量
- linux下安装软件
- C#OOP基础之类,字段,属性和方法。
- linux 进程间通信 pipe
- iOS裁剪图片成圆形
- LeetCode 328 Odd Even Linked List(奇偶链表)(Linked List)(*)
- 编译WALA
- 在线安装maven插件问题:Cannot complete the install because one or more required items could not be found.
- linux汇编学习(-)之从键盘输入输出
- 用FFmpeg命令处理音视频总结
- 多线程
- 算法训练 结点选择