Here's an example code to reproduce my problem:
#include <stdio.h>
int main()
{
char *f = "toto.txt";
char cmd[64];
sprintf(cmd, "nano %s", f);
system(cmd);
return 0;
}
If I do:
./test
Everything is fine, but if I do:
echo "blah"|./test
Nano fails:
received SIGHUP or SIGTERM
Is there a safer way to execute system commands ? I've already tried redirecting stdin.
The
system
'ed program inherits its stdin from the process that calledsystem
. In the case ofnano
(and most other text editors, I'd imagine) this is a bad thing when stdin is not the terminal.You should be able to fix it by adding
< /dev/tty
to the command string.You could check whether stdin is a tty first, and only apply the redirection when it's needed, like this:
(You're going to get bit when your
f
has any shell metacharacters in it, but that's an unrelated issue...)