linux 进程间通信 pipe
2016-01-19 13:34
423 查看
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
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学习 -- Vi命令
- centos7修改时区
- linux-0.12/boot/bootsect.S源代码阅读
- LINUX 笔记5
- Wind River Linux 6 Security Profile
- linux后台运行和关闭、查看后台任务
- linux 取消控制台报警音
- Linux下Java进程占用CPU超较高原因分析
- linux --vsftpd虚拟用户登录时 530 Login incorrect排错
- ArchLinux安裝SecureCRT破解版
- Java开发必会的Linux命令
- CentOS 国内yum源
- Linux系统中SSH命令的使用教程
- 64位centos 下编译 hadoop 2.6.0 源码
- Go语言daemon启动的解决方法.linux平台
- Linux下僵尸进程发现和杀掉方法
- linux 与windows文件夹共享实现 smab协议
- [转]linux awk命令详解
- linux 修改IP, DNS 命令
- 详解Linux下常用远程登陆命令telnet和rlogin的用法