Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::system or exec better practice?

Tags:

c++

I have a program that calls a shell script tool that I made that goes through a directory and zips up files and gets the checksum value and calls some other tools to upload the files. The operation takes roughly 3 to 4 minutes.

I call the script like this:

int result = system("/bin/sh /path/to/my/script");

I've also got the same result by using the exec() family of functions:

int child = fork();
if(child == 0) {
    execl( "/bin/sh", "sh", "/path/to/my/script", (char*)0 );
}

I know with exec you can redirect output to the parent program so it can read the output of the command line tools, but other than that when should you use system as opposed to exec?

like image 333
mjl007 Avatar asked Apr 19 '17 16:04

mjl007


People also ask

Why is system() not safe to execute external programs?

it's not portable; what works on windows might not work on linux or mac. system is a call that accepts any kind of unauthenticated shellcode, and it invokes a command interpreter that you usually do not want. Insofar it's extra overhead for adding a possible security exploit to your program.

Why not use system()?

Caveats Do not use system() from a privileged program (a set-user-ID or set-group-ID program, or a program with capabilities) because strange values for some environment variables might be used to subvert system integrity. For example, PATH could be manipulated so that an arbitrary program is executed with privilege.

Are there any differences between using exec () and system ()?

With system() you can invoke any command, whereas with exec(), you can only invoke an executable file. Shell scripts and batch files must be executed by the command shell. Basically they are entirely different used for different purposes. Moreover exec() replaces the calling process, and does not return.

How is system different from Execv?

The system( ) function works differently from the exec*( ) functions; instead of replacing the currently executing program, it creates a new process with fork( ) . The new process executes the shell with execve( ) while the original process waits for the new process to terminate.


1 Answers

Ignoring for the time being that use of system is portable while use of exec family of functions is not portable...

When you combine use of exec family of functions with other POSIX functions such as pipe, dup, wait, you get a lot more control over how to pass data between the parent process and the child process.

When you don't need any of those controls, i.e. you just want to execute a command, then using system is preferable, IMO.

like image 69
R Sahu Avatar answered Sep 23 '22 19:09

R Sahu