I'm currently reading up on and experimenting with the different possibilities of running programs from within C code on Linux. My use cases cover all possible scenarios, from simply running and forgetting about a process, reading from or writing to the process, to reading from and writing to it.
For the first three, popen()
is very easy to use and works well. I understand that it uses some version of fork()
and exec()
internally, then invokes a shell to actually run the command.
For the third scenario, popen()
is not an option, as it is unidirectional. Available options are:
- Manually
fork()
andexec()
, pluspipe()
anddup2()
for input/output posix_spawn()
, which internally uses the above as need be
What I noticed is that these can achieve the same that popen()
does, but we can completely avoid the invoking of an additional sh
. This sounds desirable, as it seems less complex.
However, I noticed that even examples on posix_spawn()
that I found on the Internet do invoke a shell, so it would seem there must be a benefit to it. If it is about parsing command line arguments, wordexp()
seems to do an equally good job.
What is the reason behind benefit of invoking a shell to run the desired process instead of running it directly?
Edit: I realized that my wording of the question didn't precisely reflect my actual interest - I was more curious about the benefits of going through sh
rather than the (historical) reason, though both are obviously connected, so answers for both variations are equally relevant.
popen("cmd1; cmd2 | grep foo")
without invoking shell? You'd have to basically implement shell inside standard library. – el.pescado Feb 20 '18 at 12:09system()
,popen()
etc. to acceptexecl()
-style argument lists, and only start a shell if you ask for that explicitly (e.g.popen(get_shell(), "-c", "$commands")
). But it is the way it is, for good or bad. OTOH, you're in luck, because you can write your own function to do what you want, and you can read the implementations ofpopen()
to crib from them. – Toby Speight Feb 21 '18 at 9:00popen()
for where I only need unidirectional communication,posix_spawn()
to start and forget about a process and wrote my own function for bidirectional communication. All seems to work well so far and it helped me to get a better understanding of the functions involved. – domsson Feb 21 '18 at 9:09