Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "system" and "exec" in Linux?

Tags:

c

linux

fork

exec

What is the difference between system and exec family commands? Especially I want to know which one of them creates child process to work?

like image 833
Kamil Avatar asked Nov 08 '09 18:11

Kamil


People also ask

Is exec a system call?

The exec system call is used to execute a file which is residing in an active process. When exec is called the previous executable file is replaced and new file is executed.

What is Linux exec?

The Linux exec command executes a Shell command without creating a new process. Instead, it replaces the currently open Shell operation. Depending on the command usage, exec has different behaviors and use cases.

What does system () do in Linux?

The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows: execl("/bin/sh", "sh", "-c", command, (char *) NULL); system() returns after the command has been completed.

Why is exec () system call used?

The exec() system call is used to replace the current process image with the new process image. It loads the program into the current space, and runs it from the entry point. So the main difference between fork() and exec() is that fork starts new process which is a copy of the main process.


2 Answers

system() calls out to sh to handle your command line, so you can get wildcard expansion, etc. exec() and its friends replace the current process image with a new process image.

With system(), your program continues running and you get back some status about the external command you called. With exec(), your process is obliterated.

In general, I guess you could think of system() as a higher-level interface. You could duplicate its functionality yourself using some combination fork(), exec(), and wait().

To answer your final question, system() causes a child process to be created, and the exec() family do not. You would need to use fork() for that.

like image 152
Carl Norum Avatar answered Sep 21 '22 13:09

Carl Norum


The exec function replace the currently running process image when successful, no child is created (unless you do that yourself previously with fork()). The system() function does fork a child process and returns when the command supplied is finished executing or an error occurs.

like image 29
BobbyShaftoe Avatar answered Sep 20 '22 13:09

BobbyShaftoe