1

Possible Duplicate:
bash: force exec’d process to have unbuffered stdout

I need to read a binary's (fceux, nes emulator) stdout to get some info, and kill it when I receive special input for a genetic algorithm that I'm trying. So basically, the problem is that the program doesn't flush his output so I receive the output only when the process ends, but it never ends because I'm suppose to kill it.

So is there a way to read from unflushed buffer child ? Even if it is not in C++, so I can add some flush and then read it finally in C++ (but that's becoming a little dirty). I've tried too using python, but didn't find a way to do it either.

Here is a chunk of my code :

int fd[2];
pid_t pid;
pipe (fd);
if ((pid = fork ()) == 0)
{
    close (fd[0]);
    dup2 (fd[1], STDOUT_FILENO);
    execl ("/usr/bin/fceux", "fceux", "Super Mario Bros.zip", NULL)
    perror ("fork");
}
else
{
    close (fd[1]);
    char buf[1];
    std::string res;
    while (read (fd[0], buf, 1) > 0)
    {
        std::cout << "Read" << std::endl;
        res += buf;
        if (res.find ("score") != std::string::npos)
        {
            std::cout << "KILL" << std::endl;
            kill (pid, SIGKILL);
        }
    }
    close (fd[0]);
}
return 0;
3
  • I don't think there is a halfway portable way to do so.
    – vonbrand
    Jan 31, 2013 at 11:49
  • Since the buffering is entirely implemented in that binary (or libaries it uses) and no one has the slightest idea about how it does it, the only sane answer at that point is: no. The file could use just any area of its memory to store its output before passing that to some i/o syscall.
    – PlasmaHH
    Jan 31, 2013 at 11:52
  • Follow the @unwind's link and tried unbuffer, that works exactly the way I wanted. Thanks a lot saved me a lot of time !
    – qwazerty
    Jan 31, 2013 at 12:27

1 Answer 1

1

Call setbuf(stdout, NULL) just before execl(). It makes stdout unbuffered.

Not the answer you're looking for? Browse other questions tagged or ask your own question.