进程间通信之管道通信(PIPE匿名管道)

#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char cwrite[1024];
    char cread[1024];
    int fd[2];
    if(pipe(fd))
    {
        perror("pipe");
        exit(errno);
    }
    int pid = fork();
    if(pid>0)
    {
        close(fd[0]);
        //关闭读管道
        sprintf(cwrite,"hello world!!\n");
        write(fd[1],cwrite,strlen(cwrite));
        wait(NULL);
    }
    else if(0 == pid)
    {
    
        close(fd[1]);
        //关闭写管道
        int len = read(fd[0],cread,sizeof(cread));
        write(STDOUT_FILENO,cread,len);
    }
    return 0;
}

pipe管道通信只适用于有血缘关系的进程间通信,不同进程间的通信不适适用匿名的管道通信

pipe管道位于内核空间块,默认大小是64k 可以使用fpathconf(fd[1],_PC_PIPE_BUF)查看

pipe通信默认是阻塞IO的 若要适用非阻塞的 pipe 可以使用

 int flags |= O_NONBLOCK;
 fcntl(fd[1], F_SETFL, flags) 使文件变为非阻塞读

pipe进程通信为单向通信,若要双向通信可以通过在开辟一条管道进行通信。

注意 fd[2]中fd[0]一般情况为3 用作读管道文件描述符,fd[1]一般是4为用作写管道描述符。

注意 若读端关闭,则写端写管道会产生SIGPIPE信号,默认写不进会终止进程。

注意 读端未读管道数据满,写段再写会阻塞。

原创。如有错漏欢迎指正。

猜你喜欢

转载自blog.csdn.net/woshichaoren1/article/details/84867193