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

标签 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;
    }

}

为什么?

输出如下:

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

此时我需要按下 Enter 以便返回到 bash 提示符。为什么?

最佳答案

At this point I will need to hit ENTER so that I return to bash prompt.

其实,你已经回到了提示符,只是你没有意识到而已。

详细来说,您在这里面临的问题是,父级不等待子级退出并在子级完成执行之前返回。因此,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

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

关于c - 为什么 execl 要求我在运行一个进程后点击 "Enter"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30590620/

相关文章:

c - 位操作和标志

cat 会破坏程序,手动 stdin 输入不会

linux - 编译vmci程序

linux - 获取由 stdin write 打印的 bash 自动补全

c - 使用 C 样式转义序列转义二进制文件

linux - 如何使用 Puppet 工具安装 Websphere Application Server

c - 有趣的可执行文件二进制转储

linux - 我们可以从文件中执行 grep 和 sed 并将输出推送到变量中吗

python - 大型 csv 文件的转置

c - 为什么我的代码中的 realloc() 和 free() 会失败?