The exec() function

Up until this point, all the child processes that we have created were copies of the parent process, with the same code and memory structure. Although this can be done, it is far less likely, as POSIX threads provide the same functionality without the issues with shared memory and IPC. POSIX threads will be discussed in more detail in Chapter 12, Learning to Program POSIX and C++ Threads.

Instead, it is more likely that calls to fork() will be followed by calls to exec(). The exec() system call is used to override the existing process with a completely new process. See the following example:

#include <unistd.h>#include <iostream>int main(void){    execl("/bin/ls", "ls", nullptr);    std::cout << "Hello World\n";}// > g++ scratchpad.cpp; ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.