by Marko Riedel
We want to collect output from a task, possibly after writing some data to its standard input. The caller of the method should have the option of a progress display that pops up after a certain time and allows the user to interrupt the task. The method returns an enumerator that iterates over the lines that were collected from the standard output of the task.
We will need two pipes, one for writing to the standard input of the task and another for reading from its standard output. We also need a modal session for the progress display. We will use the read system call to perform non-blocking reads from stdout. There is a buffer where read will store data. All of these are declared below.
The first part of the routine allocates the two pipes and collects file handles for reading and writing, resp. Furthermore we activate non-blocking reads for the file for stdout. This key idea will allow us to animate the progress panel while we are reading data. We prepare for launch by setting the tasks stdin and stdout as well as the path to the execultable and an array containing the arguments that are to be passed to the task. We are ready to launch the task. The first action is to write and close the task’s stdin. We also compute a date some time in the future (three seconds after launch in this case.)
The return value of the read call tells us what occured: there are no data when it is less than zero, it is zero on EOF and gives the number of bytes if data were copied into the buffer. We simply store the data in an NSData object allocated for this purpose. We exit the loop at EOF.
The case when there are no data but we are not at EOF is special. We need to start a modal session should the caller have requested a progress display and we have been waiting longer than three seconds. Assume that the panel progPanel was created elsewhere in the application and contains a button that sets the flag interrupted to true. We start a modal session for the panel and set the cursor.
We have to update the progress indicator should there be no data and the panel is already displayed. Here we assume that the progInd can display a value between zero and one hundred. We update the indicator and wait for 0.025 seconds whether the progress panel gets a mouse click event (mask defined above). We process the event if this is the case. This is where the user is able to click the stop button and set the flag interrupted. We terminate the task if we received an interrupt and set the data to contain an error message. The program sleeps for 0.025 seconds if there were no data, so that no busy-waiting occurs.
The remainder of the code closes the progress panel if it was displayed and ends the modal session. The return statement splits the data from stdout into lines and returns an enumerator that can be used to iterate over those lines.