4

在 bash 中,当我键入ls并按 Enter 时,二进制文件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 提示符。为什么?

4

2 回答 2

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

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

于 2015-06-02T08:07:01.840 回答
4

此时,我需要按 Enter 键才能返回 bash。

除了不,你已经在 bash 中了。但是提示符后的所有 ls 输出都使您看起来不是。继续,尝试另一个命令。

于 2015-06-02T08:06:56.793 回答