我有以下示例程序:
#include <stdio.h>
int
main(int argc, char ** argv){
char buf[100];
printf("Please enter your name: ");
fflush(stdout);
gets(buf);
printf("Hello \"%s\"\n", buf);
execve("/bin/sh", 0, 0);
}
我和当我在没有任何管道的情况下运行时,它会正常工作并返回一个sh
提示:
bash$ ./a.out
Please enter your name: warning: this program uses gets() which is unsafe.
testName
Hello "testName"
$ exit
bash$
但这在管道中不起作用,我想我知道为什么会这样,但我无法找到解决方案。示例运行如下。
bash$ echo -e "testName\npwd" | ./a.out
Please enter your name: warning: this program uses gets() which is unsafe.
Hello "testName"
bash$
我认为这与这样一个事实有关,即以这种方式gets
清空接收 EOF 并在没有错误消息的情况下立即退出。stdin
/bin/sh
但是我该如何解决这个问题(如果可能,不修改程序,如果不删除,则不删除gets
),以便即使我通过管道提供输入,我也会得到提示?
PS 我在 FreeBSD (4.8) 机器 DS 上运行它