Say I have a C program and in it I want to execute a shell command and redirect its output to file, by using the stdlib system function.

system("bash -c \"echo $HOME\" > a.txt");

Now this is for illustration, it actually doesn't work. How do I make the output redirection work? Because I'm calling bash from a function I need the process itself to do the redirecting.

  • is system() the right way to do it? You can use fork, exec and before exec change the file descriptors of the child process. Or better Use, popen function instead and you can read the file descriptors while the process is playing. – Nikhil Mulley Dec 14 '11 at 13:58
  • Suppose that my program doesn't have access to any system apis save for executing programs and passing them arguments. That's really why I need this, otherwise I'd already be using what you suggested. – sashoalm Dec 14 '11 at 14:07
  • system function takes array as argument and executes under your shell. If anything works under shell, then this should work as well. fork/exec or popen functions are generally available via stdlib, they do not need any api sort of stuff. – Nikhil Mulley Dec 14 '11 at 14:17
  • The popen and pclose functions ([see delorie.com/gnu/docs/glibc/libc_298.html ) are closely related to the system function. They allow the parent process to communicate with the standard input and output channels of the command being executed. – Nikhil Mulley Dec 14 '11 at 14:19
  • I was saying that I use system from a C program only for illustration of the problem. In reality, I'm using a function more like execve, which just starts a process and passes it a command line, and my program isn't a native binary. – sashoalm Dec 14 '11 at 14:21

THe system function already invokes a shell. This can be any sh (Bourne/POSIX) shell, not always bash. Unless you need to use bash-specific constructs, you don't need to invoke another shell inside it. If you're executing a simple command, just include the redirection in the command line. If you're executing more complex commands, you may need to put braces around the whole command sequence.

system("echo hello >somefile");
system("{ echo foo; echo bar; } >somefile");
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.