Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between popen() and system() in C

Tags:

c

system

popen

I want to execute a binary within my C code. Which is better to execute with? popen() or system()

EDIT: I tried to use system, but the process executing seems to get stuck in the end and does not return to my code.

Any suggestions on what to do?

Thanks

like image 259
Syntax_Error Avatar asked Dec 16 '11 18:12

Syntax_Error


2 Answers

popen() gives you control over the process's input or output file streams. system() doesn't. If you don't need to access the process's I/O, you can use system() for simplicity.

system() is in C89 and C99; popen() is Posix only (though the Windows API also has one).

Both functions invoke some form of a shell to execute the command (e.g. /bin/sh on Linux, and probably cmd.exe on Windows). If you want to execute an executable file directly and you are on Posix, you can also look at the exec*-family of functions in conjuction with fork() (since exec() replaces the current process).

like image 72
Kerrek SB Avatar answered Oct 20 '22 00:10

Kerrek SB


Use popen if you want to run a shell command and want the parent process to be able to talk to the child. (It hooks the child's input or output up to the stream you get back.) Otherwise, prefer the exec family of functions (likely in conjunction with fork); exec'd processes inherit most open file descriptors (including stdin, stdout, and stderr), so you can hook input and output up to whatever you like...plus, there are fewer security implications.

system is generally best avoided unless you have to run shell commands. It spawns a shell to run the command, and the shell can parse the command any way it likes. In particular, certain environment variables (like $IFS and/or $PATH) can be modified in such a way as to cause the parent to execute programs you never intended it to. Although popen appears to do the same thing, it at least provides functionality that makes it worthwhile in the general case.

like image 31
cHao Avatar answered Oct 19 '22 22:10

cHao