pipe管道

来源:互联网 发布:卖家如何联系淘宝小二 编辑:程序博客网 时间:2024/05/16 06:44
#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#define K 1024int main(void){    int result = -1;    int fd[2], nbytes;    pid_t pid;    char string[ ] = "hello, pipe";    char readbuffer[K];    int *write_fd = &fd[1];    int *read_fd = &fd[0];    result = pipe(fd);    if (result == -1) {        printf("build pipe failed.\n");        return -1;    }    pid = fork();    if (pid == -1) {        printf("fork progess failed.\n");        return -1;    }    if (pid == 0) {        close(*read_fd);        result = write(*write_fd, string, strlen(string));        return 0;    } else {        close(*write_fd);        nbytes = read(*read_fd, readbuffer, sizeof(readbuffer));        printf("recv: %d bytes, data: %s\n", nbytes, readbuffer);           }    return 0;}
0 0