I am trying to interact with an external program in C using pipe
, fork
and exec
. I want to force the external program to perform unbuffered I/O. Here's a relevant snippet from my code so far:
...
pid = fork();
if (pid == (pid_t) 0)
{
/* child process */
/* make pipe connections to standard streams */
dup2(wpipe[0], STDIN_FILENO);
dup2(rpipe[1], STDOUT_FILENO);
/* close pipe endings */
close(wpipe[0]); close(rpipe[0]);
close(wpipe[1]); close(rpipe[1]);
/* unbuffered I/O */
setvbuf(stdin, NULL, _IONBF, BUFSIZ);
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
if (execl("path/to/some_binary", "path/to/some_binary", (char *) NULL) == -1)
{
fprintf(stderr, "exec failed\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
...
This does not work because streams do not survive across exec
calls. So using setvbuf
to force unbuffered I/O does not work, because the program image (some_binary
) creates stdin and stdout streams of its own, and does not use the streams that I called setvbuf
on.
The program does work when I re-build some_binary
after adding the setvbuf
calls in its code. But how can this be done if you do not have any control over the binary you are passing to exec
? How can this be made to work for, say, a unix command like cat
or ls
?
unbuffer
command that comes with expect. – Oresteexecve
) in the child process? – Zenda