我很难找到一个好的标题,如果您有更好的想法,请随时编辑它!
我有这个程序:
#include <stdio.h>
#include <stdlib.h>
int main(){
char name[20];
scanf("%24s",name);
printf("name: %s\n",name);
system("/bin/sh");
return 0;
}
如果我启动它然后输入我的名字,它会工作得很好:
user@linux:~$ ./program
J.Doe
name: J.Doe
$
如您所见,我得到了我的 shell。但是,如果我用管道传递我的名字,我将无法访问 shell:
user@linux:~$ echo "J.Doe" | ./program
name: J.Doe
user@linux:~$
我的问题是,这里究竟发生了什么?为什么外壳是封闭的?我怎样才能通过管道传递一些命令,或者返回提示?
我想没有更多的数据要发送给程序(因为“J.Doe”已经发送给 scanf
),但我相信 shell 会挂起,等待无限期。
最佳答案
当您向程序输入一行时,它仍会运行 shell,但该 shell 会用完输入并终止。它的标准输入设备是从程序继承而来的。
类似于:
notbinsh $ echo | /bin/sh
notbinsh $
/bin/sh
执行完空脚本并终止。
关于c - 将字符串通过管道传递给 scanf 会自动结束 C 中的系统 ("/bin/sh"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39807288/