help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: why are pipeline commands (allowed to be) executed in subshells?


From: Greg Wooledge
Subject: Re: why are pipeline commands (allowed to be) executed in subshells?
Date: Mon, 12 Dec 2022 22:49:19 -0500

On Tue, Dec 13, 2022 at 04:39:14AM +0100, Philippe Cerfon wrote:
> Any I have one moreā€¦ why does this work (tried both interactively,
> non-interactively):
> 1) run a script:
> trap "echo HUP called" HUP
> sleep 1000 &
> wait $!
> 
> 2) send HUP to the bash that runs this script
> 
> This causes it to immediately print the string exit.

The "wait" command is a builtin, and it's explicltly allowed to be
interrupted by a trapped signal.

This is different from external commands.  When the shell is implicitly
waiting for a foreground external command, a trapped signal's trap will
not be executed until the foreground command terminates, and the shell
resumes control.

> In the example given in my previous mail (without the wait) the shell
> did not pass on the HUP signal to forground sleep (where it was
> waiting), so its HUP trap neither got executed.

The shell NEVER "passes on" the signal to its child processes.

In the example you showed, SIGHUP will terminate the shell, but not the
sleep.  The sleep command will continue "running" in the background
until the 1000 seconds have elapsed.

To illustrate:

unicorn:~$ cat foo
#!/bin/bash
sleep 1000 &
echo "Shell process $$ awaiting sleep process $!"
wait $!
unicorn:~$ ./foo
Shell process 969085 awaiting sleep process 969086

Then, in another terminal:

unicorn:~$ kill 969085

Then, in the first terminal:

Terminated
unicorn:~$ ps
    PID TTY          TIME CMD
   1038 pts/1    00:00:00 bash
 969086 pts/1    00:00:00 sleep
 969090 pts/1    00:00:00 ps

That sleep command will eventually die on its own, or I can kill it.

In this example, I didn't include a trap.  But doing so makes no
difference in this case.  Go ahead and try it both ways, and you'll see
the same behavior.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]