Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created September 16, 2020 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProfAvery/228b96b62bd6336fc9ff189f81c79b93 to your computer and use it in GitHub Desktop.
Save ProfAvery/228b96b62bd6336fc9ff189f81c79b93 to your computer and use it in GitHub Desktop.
C++ variant of Figure 3.8
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using std::cout;
using std::cerr;
using std::endl;
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: " << argv[0] << " PATHNAME" << endl;
return EXIT_FAILURE;
}
auto pathname = argv[1];
auto child_pid = fork();
if (child_pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (child_pid == 0) {
cout << "CHILD: child_pid = " << child_pid << "." << endl;
auto pid = getpid();
cout << "CHILD: pid = " << pid << "." << endl;
cout << "CHILD: executing " << pathname << endl;
auto ok = execl(pathname, pathname, NULL);
if (ok < 0) {
perror(pathname);
return EXIT_FAILURE;
}
} else { // child_pid > 0
cout << "PARENT: child_pid = " << child_pid << "." << endl;
int status;
auto ok = wait(&status);
if (ok < 0) {
perror("wait");
return EXIT_FAILURE;
}
cout << "PARENT: child exited with status " << WEXITSTATUS(status) << "." << endl;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment