When I was converting my comments into an answer, I tested the proposed change, and it didn't fix the problem. One fix that ought to work is to add ; exit
at the end of the string, even though that's tantamount to cheating. However, testing that also shows it doesn't finish; it is as if the ls
isn't terminating.
I went to another terminal to see whether the processes for ls
or pipe97
(my name for your code) were still around; they weren't.
- Try typing
ps
to your 'hung' process.
You should get a normal output and your prompt.
Because the parent doesn't wait for the child to exit, the prompt is lost somewhere in the output from ls
(which is quite long and produced quite slowly). Redirect the output to /dev/null
and you'll see your prompt.
- The best fix is probably to add a
wait()
loop in the parent process, so it doesn't exit until after the child does.
#include <sys/wait.h>
…
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
;
While debugging, you can print corpse
and status
so you can see what's going on.
I observe that this comment (without its preamble) remains valid:
…the close(fd[0]);
needs to be before the execl()
— remember, if it is successful, execl()
never returns (it only returns on failure). You should arguably have an error report and exit(1);
or similar after the execl()
; at the moment, you report success even on failure.
By itself, the Rule of Thumb comment is valid, but it is not actually applicable to this code — unclosed pipe descriptors aren't causing the trouble, even though one pipe descriptor that should have been closed was not closed.