为什么execl要求我在运行进程后点击"Enter"?

Kor*_*gay 4 c linux bash execl

在bash中,当我输入ls并按下回车键时,二进制文件ls将运行,我将再次返回shell提示符而不从我这边做任何事情.

但是这个用C编写的程序会阻止:

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

int main(void)
{
    pid_t other = fork();
    // other will be 0 for the child process
    // other will be the childs process' value in the parent process.

    switch(other) {
        case 0:
            printf("%s %i\n", "I am the child process!", other);
            execl("/bin/ls","ls",NULL);         
            return 0;
        default:
            printf("%s %i\n", "I am the parent process!", other);
            return 1;
    }

}
Run Code Online (Sandbox Code Playgroud)

为什么?

输出如下:

Korays-MacBook-Pro:~ koraytugay$ ./a.out 
I am the parent process! 40309
I am the child process! 0
Korays-MacBook-Pro:~ koraytugay$ AndroidStudioProjects  Movies          happyko         koray.i
Applications        Music           hello.c         koray.o
ClionProjects       Pictures        hello.sh        koray.s
Code            Public          innbound        mssql
Desktop         TheElementsFiles    innbound-pf     nono.txt
Documents       VirtualBox VMs      innbound_usage.log  svn-key
Downloads       a.out           k.txt           tugay.c
IdeaProjects        asm.asm         klinnck         webtoolkit
Koray.class     asm.hack        klinnck-pf
Koray.java      cexamples       koray.a
Library         fifa.sql        koray.c
Run Code Online (Sandbox Code Playgroud)

此时我需要点击Enter以便返回bash提示符.为什么?

Sou*_*osh 5

此时我需要点击ENTER以便返回bash提示符.

实际上,你已经回到提示,你只是没有意识到.

详细说明,你面临的问题是,父母不会等待孩子退出并事先返回孩子完成执行.因此,shell提示符返回,然后chlid进程的输出(输出ls)将打印在输出上.

如果您注意到正确,您已经收到提示,并且您的输出稍后出现.

Korays-MacBook-Pro:~ koraytugay$ ./a.out 
I am the parent process! 40309
I am the child process! 0
****Korays-MacBook-Pro:~ koraytugay$***** AndroidStudioProjects  Movies          happyko         koray.i
Applications        Music           hello.c         koray.o
ClionProjects       Pictures        hello.sh        koray.s
Code            Public          innbound        mssql
Desktop         TheElementsFiles    innbound-p
Run Code Online (Sandbox Code Playgroud)

在上面,请注意****标记的行.在那里,你得到了你的shell提示.