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.
Regards, David Alger
-- David Alger, Software Engineer Family Friendly Software, LLC |