在 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/