pipe,fork,程序如果运行if和else相同的条件怎么可能

0 c fork if-statement pipe

程序运行一次,它都将数据抛出到管道并以相互排斥的相同条件(在if和else中)将其取出.我没有到这里来的?这是如何运作的?我对这种编程没有经验.

   #include <sys/types.h>
     #include <unistd.h>
     #include <stdio.h>
     #include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

从管道中读取字符并将它们回显到stdout.

     void
     read_from_pipe (int file)
     {
       FILE *stream;
       int c;
       stream = fdopen (file, "r");
       while ((c = fgetc (stream)) != EOF)
         putchar (c);
       fclose (stream);
     }
Run Code Online (Sandbox Code Playgroud)

将一些随机文本写入管道.

     void
     write_to_pipe (int file)
     {
       FILE *stream;
       stream = fdopen (file, "w");
       fprintf (stream, "hello, world!\n");
       fprintf (stream, "goodbye, world!\n");
       fclose (stream);
     }

     int
     main (void)
     {
       pid_t pid;
       int mypipe[2];

       /* Create the pipe. */
       if (pipe (mypipe))
         {
           fprintf (stderr, "Pipe failed.\n");
           return EXIT_FAILURE;
         }

       /* Create the child process. */
       pid = fork ();
       if (pid == (pid_t) 0)
         {
           /* This is the child process.
              Close other end first. */
           close (mypipe[1]);
           read_from_pipe (mypipe[0]);
           return EXIT_SUCCESS;
         }
       else if (pid < (pid_t) 0)
         {
           /* The fork failed. */
           fprintf (stderr, "Fork failed.\n");
           return EXIT_FAILURE;
         }
       else
         {
           /* This is the parent process.
              Close other end first. */
           close (mypipe[0]);
           write_to_pipe (mypipe[1]);
           return EXIT_SUCCESS;
         }
     }
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 5

紧接着说:

pid = fork();
Run Code Online (Sandbox Code Playgroud)

你不再拥有一个程序,而是两个不同的程序(fork成功时).

这两个程序都不是同一个程序.在子进程中,fork返回0,但在父进程中返回子PID.

父运行if/ elseconstruct的一个分支,子运行另一个分支.(如果fork失败,则仅在父母中运行第三个.)