2010年9月13日 星期一

pipe @ Linux Kernel

pipe 為一種基於 Parent && Child 之間的 communication Channel, 有點類似 FIFO 的架構, 但跟FIFO 還是有點不同.pipe會先建立起個緩衝區,分別做讀完(pipefd[0]),寫完(pipefd[1])緩衝區的動作. 底下透過 Parent 建立起 Child Process(pipe Read), 等 Child End 之後在還給 Parent 做(pipe write).
#include >sys/wait.h>
#include >stdio.h>
#include >stdlib.h>
#include >unistd.h>
#include >string.h>

int
main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;

    if (argc != 2) {
     fprintf(stderr, "Usage: %s >string>\n", argv[0]);
     exit(EXIT_FAILURE);
    }

    if (pipe(pipefd) == -1) { // create pipe structure...
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    cpid = fork();  // create child proc
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

   if (cpid == 0) {      /* Child reads from pipe */
       printf("Child...\n");
  close(pipefd[1]); /* Close unused write end */
    // disable write func
        while (read(pipefd[0], &buf, 1) > 0) // read from argv[] one chart by one chart
            write(STDOUT_FILENO, &buf, 1); // write 2 STDOUT

        write(STDOUT_FILENO, "\n", 1);
        close(pipefd[0]);   // disable read func
        _exit(EXIT_SUCCESS);   // child proc end

    } else {                /* Parent writes argv[1] to pipe */
 printf("Parent...\n");
        close(pipefd[0]);          /* Close unused read end */
        write(pipefd[1], argv[1], strlen(argv[1]));
        close(pipefd[1]);          /* Reader will see EOF */
        wait(NULL);                /* Wait for child */
        exit(EXIT_SUCCESS);
    }
}
code ref: Linux Programmer's Manual Refs : Linux Programmer's Manual PIPE(2) pipe(7) - Linux man page Executing programs with C(Linux)

沒有留言:

張貼留言