我是靠谱客的博主 清爽金毛,最近开发中收集的这篇文章主要介绍Linux编程之管道,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

匿名管道:

/*      #include <unistd.h>

       int pipe(int pipefd[2]);
       参数:int pipefd[2],传出参数
            pipefd[0] 读端
            pipefd[1] 写端
        返回值:
            成功返回0,
            失败返回-1
        注意匿名管道只能用于具有亲缘关系之间的通信(父子进程,兄弟进程)
        管道默认是阻塞的,没有数据读阻塞,数据满了的话,写阻塞
*/

//子进程发送数据给父进程,父进程读取之后输出

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    //fork之前创建pipe
    int pipefd[2];
    int ret = pipe(pipefd);
    if(ret == -1){
        perror("pipe");
        exit(0);
    }
    //创建子进程
    pid_t pid = fork();
    if(pid > 0){
        //父进程
        char buf[1024] = {0};
        int len = read(pipefd[0],buf,sizeof(buf));
        printf("parent recv : %s, pid : %dn",buf,getpid());
    }
    else if(pid == 0){
        //子进程
        sleep(10);
        char* str = "hello,i am a child";
        write(pipefd[1],str,strlen(str));

    }
    return 0;
}

最后

以上就是清爽金毛为你收集整理的Linux编程之管道的全部内容,希望文章能够帮你解决Linux编程之管道所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(123)

评论列表共有 0 条评论

立即
投稿
返回
顶部