system() fails when piping stuff in

94 views Asked by At

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.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

The system'ed program inherits its stdin from the process that called system. In the case of nano (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.

sprintf(cmd, "nano %s < /dev/tty", f);

You could check whether stdin is a tty first, and only apply the redirection when it's needed, like this:

if(isatty(0))
    sprintf(cmd, "nano %s", f);
else
    sprintf(cmd, "nano %s < /dev/tty", f);

(You're going to get bit when your f has any shell metacharacters in it, but that's an unrelated issue...)