进程之间通讯------无名管道

进程之间常用的通讯方式有:

(1)无名管道(具有亲缘关系的父子进程)

(2)有名管道(任意两个进程)

(3)信号

(4)消息队列

(5)内存共享

(6)信号量(一般是进程之间同步的手段,一般配合互斥锁、条件变量一起使用)

(7)socket套接字

现在介绍最简单的无名管道,用到的API函数如下:


比较简单,我们可以定义一个数组pipe_fd[2]来表示管道的两端,其中pipe_fd[0]是从管道读取数据,pipe_fd[1]是向管道写入数据,由于只用于父进程和子进程之间通信,需要在创建子进程之前创建管道,这样子进程才能继承创建的管道,具体代码如下

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<errno.h>
#include<sys/wait.h>
/**
 * 无名管道是半双工的,管道两端的进程任何时候要么是读,要么是写
 * *
 */
int main()
{


    /*******管道的两端******/
    int pipe_fd[2];
    pid_t pid;
    char buf[11];
    /*********创建管道**********/
    if(pipe(pipe_fd)<0)
    {
        perror("create pipe fail!");
        exit(1);
    }
    /********创建子进程*************/
    pid = fork();
    if(pid <0)
    {
        perror("create child fail");
        exit(1);
    }
    else if(pid>0)
    {
        /**********设置父进程******/
        /*********向管道写入之前要关闭读端*******/
        close(pipe_fd[0]);
        write(pipe_fd[1],"hello mips\n",11);
    }
    
    else
    {
        /***********设置子进程*******/
        /***********读取管道的时候要关闭写端*****/
        close(pipe_fd[1]);
        read(pipe_fd[0],buf,11);
        /***********输出到屏幕********/
        printf("\n");
        printf("read:%s\n",buf);
        exit(0);
    }

}

编译结果如图:


在mt7688板子上运行结果:


好了,就这么多。

猜你喜欢

转载自blog.csdn.net/u012154319/article/details/80856222