父子进程通过匿名管道通信


/*
    #include <unistd.h>
        int pipe(int pipefd[2]);
            功能:创建匿名管道,用于进程间通信
            参数:
                - int pipefd[2] 这个数组是一个传出参数
                - pipefd[0]对应管道的读端
                - pipefd[1]对应管道的写端
            返回值:
                成功:返回0
                失败:返回-1
    管道默认是阻塞的:如果管道中没有数据,read阻塞,如果管道满了,write阻塞

    注意:匿名管道只能用于有关系的进程

    ulimit -a 
    - 可以查看管道缓冲大小
    - 一块的大小为512字节

    fpathconf(pipefd[0],_PC_PIPE_BUF);
    - 查看管道大小
*/
//子进程发送数据给父进程
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

int main()
{
    //管道的创建需要在fork之前,会得到两个文件描述符
    int pipefd[2];//piped[0]读取端口,pided[1]写入端口
    int ret=pipe(pipefd);
    if(ret==-1)
    {
        perror("pipe");
        exit(0);
    }

    //创建子进程
    pid_t pid=fork();
    if(pid>0)
    {
        //父进程
        printf("i am parent,pid: %d\n",getpid());

        //从管道的读取端读取数据
        char buf[1024]={0};
        while (1)
        {
            int len=read(pipefd[0],buf,sizeof(buf));//read会返回读取到的个数
            printf("parent recv %s,pid: %d\n",buf,getpid());
            //都不用暂停,因为读取时管道没有数据就会自动阻塞

            char* str="hello,i am parent";
            write(pipefd[1],str,strlen(str));//注意求字符串长度不用sizeof
            sleep(1);
        }
    }
    else
    {
        //子进程
        printf("i am child,pid: %d\n",getpid());
        //向管道中写入数据
        while (1)
        {
            char* str="hello,i am child";
            write(pipefd[1],str,strlen(str));//注意求字符串长度不用sizeof
            sleep(1);

            //读数据
            char buf[1024]={0};
            int len=read(pipefd[0],buf,sizeof(buf));//read会返回读取到的个数
            printf("child recv %s,pid: %d\n",buf,getpid());
        }
        
    }
    return 0;
}

posted @ 2023-02-09 10:38  小秦同学在上学  阅读(28)  评论(0编辑  收藏  举报