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















0 0
原创粉丝点击