Re: retrieving results of system() call from stdout?
Re: retrieving results of system() call from stdout?
- Subject: Re: retrieving results of system() call from stdout?
- From: Michael Smith <email@hidden>
- Date: Fri, 23 Mar 2007 13:58:18 -0700
On Mar 23, 2007, at 12:03 PM, email@hidden wrote:
i'm writing a C++ GUI app that makes use of the command line to do
somthing.
say i've got a command line utility "foo" that takes a whatever and
ouputs a modifided whatever, but while it's processing it gives
feedback like:
foo working: 20%
foo working: 37%
foo working: 49%
foo working: 63%
foo working: 75%
etc etc.
how can i:
1) make system() return immediately (it t as simple as putting a "&"
at the end of the string?)
2) *read* from stdout or get notified when a new string is pushed
to it?
3) *read* from stderr to see if something bad happened?
Canonically, the best way to do this is to fork a child process with
descriptors set appropriately. The use of system/popen is generally
discouraged.
You would typically do something like this:
int sout_pipe[2];
int serr_pipe[2];
int child_pid;
/* create pipes and mark them non-close-on-exec */
pipe(sout_pipe);
fcntl(sout_pipe[1], F_SETFD, fcntl(sout_pipe[1], F_GETFD) & ~1);
pipe(serr_pipe);
fcntl(serr_pipe[1], F_SETFD, fcntl(serr_pipe[1], F_GETFD) & ~1);
/* go our separate ways */
child_pid = fork();
/* in the child process, re-arrange stdout/err and run the tool */
if (child_pid == 0) {
close(0);
close(1);
dup2(sout_pipe[1], 1);
close(2);
dup2(serr_pipe[2], 2);
execl(absolute_path_to_tool, arguments...)
}
Once you've fired off the tool, you can use select/poll on the
descriptors sout_pipe[0] (for the tool's standard out) and serr_pipe
[0] (for the tool's error output).
Inside the tool, if you are using standard I/O you would typically
want to either set line buffering (assuming you want to use line
delimiters to separate messages), or explicitly flush in order to
avoid synchronisation issues.
Obviously you can use the same trick to pass commands to the tool on
standard in.
It's also important to reap the tool with one of the wait(2) family
of calls. See the documentation for fork(2), pipe(2), exec(3) and
dup2(2) for more information. I also strongly encourage you to pick
up a copy of W. Richard Stevens' "Advanced Programming in the Unix
Environment".
= Mike
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden