bug-bash
[Top][All Lists]
Advanced

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

Re: kill $! won't kill the last command in asynchronous list


From: Oğuz
Subject: Re: kill $! won't kill the last command in asynchronous list
Date: Wed, 1 Apr 2020 19:16:03 +0300

Thanks for the reply.

1 Nisan 2020 Çarşamba tarihinde Chet Ramey <address@hidden> yazdı:

> On 4/1/20 12:19 AM, Oğuz wrote:
> > $ bash -c '{ sleep 15; } & pstree -p $!; kill $!; echo $?'
> > bash(6955)───sleep(6959)
> > 0
> > $ pkill -e sleep
> > sleep killed (pid 6959)
> >
> > As seen above, kill $! doesn't kill `sleep` if it's enclosed in curly
> > braces. Dropping curly braces, or execing sleep (e.g `{ exec sleep 15;
> }`)
> > fixes this problem, but I didn't understand why.
>
> The braces enclose a group command, and that group command is what's
> started in the background. That process is effectively a copy of the shell
> that runs the command list contained in the group command (there can be
> more than one command, though your example doesn't include that).
>
> Since that shell is what's forked to execute the command list, it's the
> process whose pid ends up in $! and the one that receives the SIGTERM.
> Unless the shell kills the process it's waiting for when it receives the
> SIGTERM, or you send the signal to the entire process group, sleep won't
> see it.
>
>
You are right, I think I was just confused. But this is exactly where I'm
stuck now;
1) I couldn't figure out how to get shell to kill the process it's waiting
for,
2) kill -- -$! says no such process group is found; I couldn't figure out a
reliable way to kill $! and its children. Sending signal to -$$ works most
of the time, but $$ is not guaranteed to be the process group ID if I'm not
mistaken.

Should I ask this on a Q&A forum?

There are various race condition here. Shells always ignore SIGTERM. One of
> the first things a subshell does after the shell forks it is reset the
> SIGTERM handler to SIG_DFL. If the background process doesn't run until the
> rest of the parent's command list executes, the parent will send a SIGTERM
> to a process that's still ignoring it. It's also possible that the SIGTERM
> arrives before the sleep is executed and kills the shell, so the sleep
> never runs at all.
>
> Under most circumstances, but not all, I would expect the shell to be
> killed and the sleep to survive.
>
> --
> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>                  ``Ars longa, vita brevis'' - Hippocrates
> Chet Ramey, UTech, CWRU    address@hidden    http://tiswww.cwru.edu/~chet/
>


-- 
Oğuz


reply via email to

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