I'm trying to invert a string in C++ using fork(), such that each process prints at most one character. My thinking is that after printing each character, I fork into a new process, end the parent process, and continue. Here is my code:
#include <string>
#include <iostream>
#include <unistd.h>
/*
Recursively print one character at a time,
each in a separate process.
*/
void print_char(std::string str, int index, pid_t pid)
{
/*
If this is the same process,
or the beginning of the string has been reached, quit.
*/
if (pid != 0 || index <= -1)
return;
std::cout << str[index];
if (index == 0)
{
std::cout << std::endl;
return;
}
print_char(str, index-1, fork());
}
int main(int argc, char** argv)
{
std::string str(argv[1]);
print_char(str, str.length()-1, 0);
}
However, when testing the code with the argument "hey", it prints "yeheyy". My understanding of fork() is that it creates a duplicate process with a copy of the memory space, and whenever I mentally "walk through" the code it seems like it should work, but I cannot figure out where my logic is failing.
wait()or one of its relatives. The first process needs to fork a child that will print the rest of the string, and wait for it to complete before printing its character (and a newline). I’ll also observe that I cannot think of a circumstance where I’d usefork()as a parameter to a function call.