Last active
August 31, 2021 23:23
-
-
Save ProfAvery/5908e3a7cbaf173aed262ea912d0ed79 to your computer and use it in GitHub Desktop.
C++ variant of cpu-api/p4.c (Figure 5.4)
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
CXXFLAGS = -g -std=c++17 -Wall -Wextra -Wpedantic -Werror | |
all: p4 | |
# Note: using implicit rule for .cpp files to create p4 | |
.PHONY: clean test | |
test: p4 | |
./p4 && cat p4.output | |
clean: | |
rm -f p4 p4.output |
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 <cstdio> | |
#include <cstdlib> | |
#include <cstring> | |
#include <cassert> | |
#include <vector> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/wait.h> | |
using std::vector; | |
int | |
main(int argc, char *argv[]) | |
{ | |
(void)argc, (void)argv; | |
auto rc = fork(); | |
if (rc < 0) { | |
// fork failed; exit | |
perror("fork failed"); | |
exit(EXIT_FAILURE); | |
} else if (rc == 0) { | |
// child: redirect standard output to a file | |
close(STDOUT_FILENO); | |
open("./p4.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU); | |
// now exec "wc"... | |
vector<char *> myargs; | |
myargs.push_back(strdup("wc")); // program: "wc" (word count) | |
myargs.push_back(strdup("p4.cpp")); // argument: file to count | |
myargs.push_back(NULL); // marks end of array | |
execvp(myargs[0], myargs.data()); // runs word count | |
} else { | |
// parent goes down this path (original process) | |
auto wc = wait(NULL); | |
assert(wc >= 0); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment