进程间通信——管道通信

来源:互联网 发布:epub手机阅读软件 编辑:程序博客网 时间:2024/05/17 21:53

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\n",childpid);    if(childpid==0){        close(fd[0]);//读管道        write(fd[1],writebuf,(strlen(writebuf)+1));        printf("this is father\n");        printf("childpid in if is %d\n",childpid);        exit(0);    }    else{        close(fd[1]);//写管道        printf("childpid in else %d \n",childpid);        read(fd[0],readbuf,100);        printf("childpid in else %d \n",childpid);        printf("received string:%s\n",readbuf);    }return 0;}

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

[root@bogon bp]# ./a.outafter fork 85552childpid in else 85552 after fork 0this is fatherchildpid in if is 0childpid in else 85552 received string:this if from centos
0 0
原创粉丝点击