Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Last active August 31, 2021 23:23
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/5908e3a7cbaf173aed262ea912d0ed79 to your computer and use it in GitHub Desktop.
Save ProfAvery/5908e3a7cbaf173aed262ea912d0ed79 to your computer and use it in GitHub Desktop.
C++ variant of cpu-api/p4.c (Figure 5.4)
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
#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