[SOLVED] How to Close Child Processes

I'm having an odd issue where Child processes are not being closed after their scope has exited, and I'm at a loss as to how to force them to close. It would seem that I cannot use the wait method after I'm finished reading the Child's piped stdout/stderr messages as that causes an issue with the borrow checker stating that I've already borrowed child.stderr/child.stdout previously.

Sample code attached, edited for stand-alone demonstration. The code in the example should simply execute the echo command 64,000 times and automatically close echo after echo has echoed what it was supposed to echo, but each echo process lingers around, gradually building up until an OS error 11 occurs. My question is why it's not closing the child processes when Child is dropped.


It's worth taking a look at the documentation for Child. It says

Take note that there is no implementation of Drop for child processes, so if you do not ensure the Child has exited then it will continue to run, even after the Child handle to the child process has gone out of scope.

Calling wait (or other functions that wrap around it) will make the parent process wait until the child has actually exited before continuing.

So that explains why the child processes are not being 'closed' (or, more accurately, reaped - as you may know they're not actually still around, it's just an entry in the process table).

Assuming that the output function is just meant to handle the output, the best solution is probably to pass a mutable reference to the child process into output, rather than transferring ownership. Then you can wait on the process in the loop. See main.rs ยท GitHub

I see that the missing key that I wasn't able to figure out was the as_mut() that you are using for gaining access to the Child's stdout/stderr fields which keeps the borrow checker happy.