您的位置:首页 > 运维架构 > Linux

linux 下父子进程通过管道传输数据

2017-05-12 15:48 204 查看
#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <string.h>

#include <fcntl.h>

int main(int argc,char* argv[])

{

        int status;

        int fd[2];

        int pi=pipe(fd);

        char *buf=(char*)malloc(sizeof(char)*20);

        memset(buf,0,sizeof(char)*20);

        if(pi==-1)

                perror("pipe");

        pid_t pid=fork();

        if(pid==-1)

                perror("fork");

        if(pid==0){

                printf("this is a child\n");

                close(fd[0]);

                write(fd[1],"write something",20*sizeof(char));

        }else{

                sleep(1);

                waitpid(pid,&status,0);

                printf("this is father\n");

                close(fd[1]);

                read(fd[0],buf,20*sizeof(char));

                printf("%s\n",buf);

                free(buf);

        }

        printf("main \n");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: