Coder Perfect

In Linux, what is the difference between “system” and “exec”?


What is the difference between the commands in the system and exec families? I’m particularly curious in which of these makes the child process work.

Asked by Kamil

Solution #1

system() uses sh to handle your command line, allowing you to use wildcard expansion and other features. exec() and its friends create a new process image in place of the present one.

Your software continues to execute while system() returns information about the external command you called. Your process is annihilated when you use exec().

I suppose you might think of system() as a higher-level interface in general. You could use a combination of fork(), exec(), and wait() to replicate its capabilities ().

To answer your last point, system() does not produce a child process, whereas the exec() family does. For that, you’d need to use fork().

Answered by Carl Norum

Solution #2

When the exec function succeeds, it replaces the currently operating process image; no child is generated (unless you do it yourself using fork()). When the command passed is finished executing or an error occurs, the system() method forks a child process and returns.

Answered by BobbyShaftoe

Solution #3

The specified command will be executed in a child process created by system(). The current process will be replaced by the invocation of the new executable that you specify using exec(). If you want to use exec to launch a child process, you must first fork() your process.

Answered by Timo Geusch

Solution #4

To develop a procedure, follow these steps:

To run a software that will replace the current image:

To wait for a child’s process to be completed:

To run a program as a child process in a shell and wait for it to complete:

To obtain the man pages for all of the preceding, go to:

   $ man 2 fork execve wait
   $ man 3 system

Answered by DigitalRoss

Solution #5

system() will launch your system’s default command shell, which will run the command string supplied as an argument, which may or may not start further processes, depending on the command and system. In either case, a command shell process will be started.

You can use system() to run any command, whereas exec() can only run an executable file. The command shell must execute shell programs and batch files.

They are fundamentally distinct and are utilized for various objectives. Furthermore, exec() does not return and replaces the calling process. A better analogy would be between system() and spawn() (). While system is easier to use, it only provides a value that indicates if the command shell was invoked and nothing about the command’s success. The exit code of a process can be obtained using spawn(); non-zero values are used to signify error conditions by convention. spawn(), like exec(), must call an executable rather than a shell script or a built-in command.

Answered by Clifford

Post is based on