Re: Redirecting Output for a fork()'d Process
Re: Redirecting Output for a fork()'d Process
- Subject: Re: Redirecting Output for a fork()'d Process
- From: "Duane Murphy" <email@hidden>
- Date: Thu, 12 Apr 2007 09:46:18 -0700
You need to take a look at on of the Steven's books or there must be
some reference to this on the web.
This is a very common thing to do and what every shell program does to
redirect output.
The basic idea is that after forking, you connect the stdin, stdout,
stderr of the forked process to a known descriptor in the parent
process. Then exec the child process. This has the affect of having all
writes to the stdout in your tool go directly to a descriptor in the parent.
This is really text book stuff. There should be examples somewhere. :-)
Enjoy,
...Duane
--- At Thu, 12 Apr 2007 10:51:37 -0500, David Alger wrote:
>Hi Guys,
>
>I'm writing a Carbon app that needs to use fork and execv to spawn a
>command line tool. I also need to be able to read the output of the tool
>as it's running to provide progress bar updates. I came up with the
>following, but am not sure if it's the best way (or proper) to do what I
>want to accomplish. I'm also not sure if any of the duplication of file
>descriptors and opening of files here is creating a memory leak.
>
>Basically what I'm trying to do is to have the output of the tool
>redirected to a file that I will read from while it is running, but I
>still want the output of my app to go to the normal stdout stream.
>
>In the below code error checking has been removed. Also, some variables
>that are used here are declared in the function that contains this block.
>_START_CODE_
>
>//...
>
>{
> int d;
> int stdoutS, stderrS;
> FILE* stream;
> EventLoopTimerRef timerRef;
> ProgressUpdateTimerUserData ud;
>
> unlink(redirectPath); //remove the old output file to start with a
fresh file
> stream = fopen(redirectPath, "a+");
> d = fileno(stream);
>
> stdoutS = dup(STDOUT_FILENO);
> stderrS = dup(STDERR_FILENO);
> dup2(d, STDOUT_FILENO);
> dup2(d, STDERR_FILENO);
>
> if((pid = fork()) == 0)
> {
> execv(commandPath, argv);
> }
>
> dup2(stdoutS, STDOUT_FILENO);
> dup2(stderrS, STDERR_FILENO);
> stream = fopen(redirectPath, "r");
>
> ud.pid = pid;
> ud.progWindow = progWindow;
> ud.stream = stream;
> ud.parentWindow = window;
>
> //...
> //Timers and event loop code here. Event loop returns on completion of
>the spawned process.
> //...
>
> fclose(stream);
>}
>
> //...
>
>_END_CODE_
>
>Any help is greatly appreciated.
...Duane
_______________________________________________
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