In C++, calling fork when cin is a bash heredoc causes repeated input fragments In C++, calling fork when cin is a bash heredoc causes repeated input fragments bash bash

In C++, calling fork when cin is a bash heredoc causes repeated input fragments


I was able to reproduce this problem, not only using the heredoc but also using a standard file redirection.

Here is the test script that I used. In both the first and second cases, I got a duplication of the second line of input.

./a.out < Input.txtechocat Input.txt | ./a.outecho./a.out <<EOFhello worldgoodbye worldEOF

Closing the stdin before exiting in the child seems to eliminate both of the problems.

#include <iostream>#include <sstream>#include <unistd.h>#include <sys/wait.h>#include <limits>int main(int argc, char **argv){    std::string line;    while (std::getline(std::cin, line)) {        pid_t pid = fork();        if (pid == 0) { // child            close(STDIN_FILENO);            break; // exit after first closing stdin        }        else if (pid > 0) { // parent            waitpid(pid, nullptr, 0);        }        else { // error            perror("fork");        }        std::cout << getpid() << ": " << line << "\n";    }    return 0;}