I'm trying to use popen()
to catch the stderr of a call, but of course it doesn't seem to be doing that. Any ideas?
My code looks more or less like this:
popen("nedit", "r");
But I'm getting all this garbage about non-utf8 on my screen...
I'm trying to use popen()
to catch the stderr of a call, but of course it doesn't seem to be doing that. Any ideas?
My code looks more or less like this:
popen("nedit", "r");
But I'm getting all this garbage about non-utf8 on my screen...
popen
gives you a file handle on a process' stdout, not its stderr. Its first argument is interpreted as a shell command, so you can do redirections in it:
FILE *p = popen("prog 2>&1", "r");
or, if you don't want the stdout at all,
FILE *p = popen("prog 2>&1 >/dev/null", "r");
(Any other file besides /dev/null
is acceptable as well.)
If you want to discard all of the error messages, then you can use:
popen("nedit 2>/dev/null", "r");
if you need both stdout and stderr streams, you can open an extra pipe and redirect child stderr to it:
if (pipe(pfd) < 0)
return -1;
perr = fdopen(pfd[0], "r");
snprintf(command, LINE_LEN, "... 2>&%d", pfd[1]);
if (pout = popen(command, "r")) {
close(pfd[1]);
while (fgets(line, LINE_LEN, pout) != NULL)
...
while (fgets(line, LINE_LEN, perr) != NULL)
...
pclose(pout);
}
fclose(perr);
close(pfd[0]), close(pfd[1]);
As Andrew pointed out, if command
generates lots of output/errors, you must handle the streams more carefully (see comments below).