pipe2.c

来自「Linux程序设计(原书第2版)源码」· C语言 代码 · 共 42 行

C
42
字号
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>int main(){    int data_processed;    int file_pipes[2];    const char some_data[] = "123";    char buffer[BUFSIZ + 1];    pid_t fork_result;    memset(buffer, '\0', sizeof(buffer));    if (pipe(file_pipes) == 0) {        fork_result = fork();        if (fork_result == -1) {            fprintf(stderr, "Fork failure");            exit(EXIT_FAILURE);        }// We've made sure the fork worked, so if fork_result equals zero, we're in the child process.        if (fork_result == 0) {            data_processed = read(file_pipes[0], buffer, BUFSIZ);            printf("Read %d bytes: %s\n", data_processed, buffer);            exit(EXIT_SUCCESS);        }// Otherwise, we must be the parent process.        else {            data_processed = write(file_pipes[1], some_data,                                   strlen(some_data));            printf("Wrote %d bytes\n", data_processed);        }    }    exit(EXIT_SUCCESS);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?