两个条件如何在if-ifelse-else语句中起作用?

mal*_*yeb 4 c if-statement

我的教授在C中展示了以下示例:

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main() {
   pid_t pid;

   /* fork another process */
   pid = fork();
   if (pid < 0) { /* error occurred */
         fprintf(stderr, "Fork Failed");
         return 1;
   }
   else if (pid == 0) { /* child process */
         execlp("/bin/ls", "ls", NULL);
   }
   else { /* parent process */
        /* parent will wait for the child */
        wait (NULL);
        printf("Child Completed its execution\n");
   }

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我编译并运行它.我在这段代码中看到了一个奇怪的行为:

打印'ls'程序/命令的结果,这是在else if条件下,但也打印出字符串"Child Completed its execution \n",它也是在else中打印的.

这不是一个奇怪的行为吗?

mr-*_*-sk 5

不,你分叉了.有两个进程在运行.一个报告了ls,另一个报告了printf().

具体来说,子/ forked进程执行/ bin/ls和父进程调用printf(),你看到的输出.