进程间通信——管道通信

pipe管道通信

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
int main(){
    pid_t childpid;
    int fd[2];
    pipe(fd);
    char writebuf[]="this if from centos";
    char readbuf[100];
    if((childpid=fork())==-1){
        perror("fork error");
        exit(1);
    }
    printf("after fork %d
",childpid);
    if(childpid==0){
        close(fd[0]);//读管道
        write(fd[1],writebuf,(strlen(writebuf)+1));
        printf("this is father
");
        printf("childpid in if is %d
",childpid);
        exit(0);
    }
    else{
        close(fd[1]);//写管道
        printf("childpid in else %d 
",childpid);
        read(fd[0],readbuf,100);
        printf("childpid in else %d 
",childpid);
        printf("received string:%s
",readbuf);
    }
return 0;}

执行效果如下,这个我也搞得不是很清楚,自己看运行结果吧,那些打印语句就是我故意写上去,看看运行结果的

[root@bogon bp]# ./a.out
after fork 85552
childpid in else 85552 
after fork 0
this is father
childpid in if is 0
childpid in else 85552 
received string:this if from centos
原文地址:https://www.cnblogs.com/biaopei/p/7730656.html