0

If I just run sleep 1 & in bash, the sleep process will get reaped almost instantly after it dies. This happens whether job control is enabled or disabled. Is there a way I can make bash hold off on reaping the process until I do something like wait or fg? E.g.:

sleep 1 & sleep 2 ps -ef | grep defunct # I want this to show the sleep 1 process wait ps -ef | grep defunct # But now it should be gone 
3
  • 1
    I don't understand. Are you actually talking about sleep 1? Isn't it normal that it will be gone after one second? Commented Apr 19, 2023 at 5:23
  • 1
    @TomYan, yes and no. When a process dies, its parent gets the SIGCHLD signal, which prompts it to call wait() to fetch the exit status of the child. Before that happens, the dead process is still lying around in the process list as a so-called zombie process. You usually don't see them, since most programs that fork children just clean them up immediately. Commented Apr 19, 2023 at 9:27
  • Shell scripting is relatively high level and the shell does a lot of tidying up as it goes. If you don't want this level of support you're going to need to use a programming language such as Python, Perl, C, etc. Commented Apr 19, 2023 at 10:10

1 Answer 1

1

I'm not sure why you would want to, but you can interpose another process to reap the child, then pause that process so it cannot handle the SIGCHLD signal. Eg:

bash -c 'sleep 1 & kill -STOP $$' & pid=$! sleep 2 ps -ef|grep defunct ps f kill -CONT $pid 

The ps f output showing the T and Z states would be

 8023 pts/2 S+ 0:00 \_ /bin/bash mytest 8024 pts/2 T+ 0:00 \_ bash -c sleep 1 & kill -STOP $$ 8026 pts/2 Z+ 0:00 | \_ [sleep] <defunct> 8029 pts/2 R+ 0:00 \_ ps f 
2
  • I suppose the approach will be subjected a race? Commented Apr 19, 2023 at 9:56
  • Sure. It is just a proof of concept since we don't know what the OP really wants to do. You can make it more robust by giving the pause action within the child to the parent, e.g. with bash -c '(kill -STOP $$; exec sleep 1) & wait' & Commented Apr 19, 2023 at 12:43

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.