[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Help-bash] Why is backgrounded work not considered a 'job' if launched
From: |
Hales |
Subject: |
[Help-bash] Why is backgrounded work not considered a 'job' if launched inside of something being piped to? |
Date: |
Thu, 27 Dec 2018 22:30:45 +1100 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.3.3 |
Hello help-bash,
I have been having trouble with 'wait' and 'jobs' pretending there are
no jobs when there are.
Here is a simplified script that demonstrates my problem:
**
###############################################
#!/bin/bash
example_worker()
{
echo "Starting worker $1"
sleep 3
echo "Finishing worker $1"
}
echo -e 'one\ntwo\nthree' | while read line
do
example_worker $line &
done
echo '-- Jobs --'
jobs
echo '-- Waiting for jobs to finish --'
wait
echo '-- Script over --'
###############################################
*
*When the shell gets to the 'jobs' and 'wait' commands it should find
three jobs are running in the background. Instead it finds none, prints
' -- Script over --' and leaves me back at my interactive shell.
About 3 seconds later the jobs actually finish and I get their output
printed all over my interactive shell prompt.
The problem appears to be caused by piping data to a loop. This next
script avoids using a pipe and hence does not suffer this problem:
###############################################
#!/bin/bash
example_worker()
{
echo "Starting worker $1"
sleep 3
echo "Finishing worker $1"
}
for num in one two three
do
example_worker $num &
done
echo '-- Jobs --'
jobs
echo '-- Waiting for jobs to finish --'
wait
echo '-- Script over --'
###############################################
This time the script actually thinks it has jobs and waits. As I expect
it should.
What's going on here? Are commands run on the RHS of a pipe not
considered part of the current shell and its jobs?
Side notes:
1) Functions are not necessary to trigger this bug. You can replace the
func call with a "wait 3 &" and the problem still occurs.
2) Both 'while' and 'for' are affected, so I presume it's to do with
anything on the RHS of a pipe. If you modify the second script to have
'echo moo | for num in one two three' then it starts having the problem
again.
3) GNU bash, version 4.4.23(1)-release (x86_64-unknown-linux-gnu)
4) I'm aware the example scripts above have race conds in their
printing, it's unrelated.
Regards, Hales
3) Text printing in the scripts above suffers race conds, but this isn't
related to my issue.
- [Help-bash] Why is backgrounded work not considered a 'job' if launched inside of something being piped to?,
Hales <=