The exec*() family of functions replaces the current current process with the new executable. Thus, it is not possible to execute several commands, because as soon as you call execve() , your own program no longer starts - the process now executes a new program.
The existing answer shows the "classic" approach of using fork() to create a new process and call the exec*() function. This has a bit of overhead for copying some process related resources, which are immediately replaced by calling exec*() . To solve this inefficiency, vfork() was invented. vfork() must not do any copying and therefore do anything other than calling _exit() , or one of the exec*() functions in the child created by vfork() is undefined behavior.
This is a huge source of errors and was later removed from the POSIX standard, so you should not use vfork() in a modern program. There is currently a new way to solve this problem: posix_spawn() . This function creates a new process directly with the new executable. Since this is a good match for what you are trying to achieve in your question, here is a tiny use case:
#include <stdio.h> #include <spawn.h> #include <sys/types.h> #include <sys/wait.h> extern char **environ; int main(void) { char *argv[][3] = { { "echo", "First command", 0}, { "echo", "Second command", 0} }; for (int i = 0; i < 2; ++i) { pid_t pid; if (posix_spawn(&pid, "/bin/echo", 0, 0, argv[i], environ) != 0) { fputs("Error spawning child.\n", stderr); } else { // could get exit code etc here, see // https://linux.die.net/man/2/waitpid wait(0); } } return 0; }
source share