Reputation: 1394
In Windows, you can execute a process using CreateProcess().
Now I want to know how to execute a process in Linux, so far I only found that you can do that by calling fork()
and then calling exec()
.
Is this the only way to execute a process in Linux?
Upvotes: 1
Views: 1874
Reputation: 181714
Linux provides both high-level and low-level interfaces for starting new processes.
The primary low-level interface is the one you have already discovered: fork()
. This is often followed quickly by one of the several exec()
functions, but an exec()
is unneeded if it is satisfactory for the new process to execute the same code as the original. That's more common than it may sound to someone more used to the Windows API.
POSIX also defines posix_spawn()
family, which serve as special-purpose alternatives to fork()
+ exec()
for certain circumstances to which the latter are not well suited. posix_spawn()
is implemented on Linux via the clone()
library function (see next).
Although they are not in POSIX, Linux also provides clone()
and vfork()
as alternatives to fork()
. On modern Linux these use the same system system call that fork()
does, but not the fork()
library function itself. There's not much reason to use vfork()
any longer -- it is perhaps indicative that POSIX used to have it, but removed it nearly a decade ago. Linux-specific clone()
, on the other hand, has some interesting behaviors that are occasionally useful. It provides a more general interface to the fork system call than any of the other functions discussed here do, but it is not portable. Generally speaking, prefer fork()
unless you need something it cannot provide.
Linux provides some higher-level interfaces as well. The primary two are system()
, which executes a shell command and waits for it to complete, and popen()
, which launches a shell command with either its standard input or standard output connected to a pipe, by which the concurrently-running parent process can communicate with it. Both of these are specified by POSIX, and on POSIX systems they are specified to operate via fork()
+ exec()
. Of course Windows has system()
, too, and _popen()
, but not fork()
or any direct analog.
Overall, then, a userspace Linux process can start a new process only by forking, but that is to be distinguished from calling the fork()
library function, even indirectly. There are at least six different C library functions in GNU / Linux that can serve as an interface for starting a new process. Some of those interfaces furthermore permit the new process to execute the same code (a copy of the process image of the original) indefinitely, which is sometimes a useful thing to do. It is the fork()
part of fork()
+ exec()
that starts a new process; the exec()
part merely changes what code the new process runs.
Upvotes: 2