0

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.

2
  • There are fairly better and easier methods to invert a string. Commented Oct 2, 2017 at 5:11
  • You’re probably going to need to use 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 use fork() as a parameter to a function call. Commented Oct 2, 2017 at 5:13

1 Answer 1

2

It seems, your code is OK, but you have trouble with cout.

try change only the output line

std::cout << str[index];

with

std::cout << str[index] << std::flush;

tried it and worked for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.