Created
September 16, 2020 06:55
-
-
Save ProfAvery/228b96b62bd6336fc9ff189f81c79b93 to your computer and use it in GitHub Desktop.
C++ variant of Figure 3.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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