Skip to main content
short explanation
Source Link
user313992
user313992

If you're on a GNU/Linux system or have coreutils installed, use flock(1) (maybe using the executable/command itself as the lockfile):

% cat linger
echo -n $$; date +%s; sleep $1

% flock ./linger ./linger 8 &
[3] 5941
% 59421598557788

% flock ./linger ./linger 9 &
[4] 5945
% flock ./linger ./linger 11 &
[5] 5946
% 59471598557796
59501598557805

[3]   Done                    flock ./linger ./linger 8
[4]   Done                    flock ./linger ./linger 9
[5]   Done                    flock ./linger ./linger 11

What you're trying to do doesn't work, because for the shell stopping a command is like it immediately exiting with a non-zero (fail) status:

% sleep 10 || echo FAIL
^Z
[3]+  Stopped                 sleep 10
FAIL
% fg
sleep 10
% echo $?
0

If you're on a GNU/Linux system or have coreutils installed, use flock(1) (maybe using the executable/command itself as the lockfile):

% cat linger
echo -n $$; date +%s; sleep $1

% flock ./linger ./linger 8 &
[3] 5941
% 59421598557788

% flock ./linger ./linger 9 &
[4] 5945
% flock ./linger ./linger 11 &
[5] 5946
% 59471598557796
59501598557805

[3]   Done                    flock ./linger ./linger 8
[4]   Done                    flock ./linger ./linger 9
[5]   Done                    flock ./linger ./linger 11

If you're on a GNU/Linux system or have coreutils installed, use flock(1) (maybe using the executable/command itself as the lockfile):

% cat linger
echo -n $$; date +%s; sleep $1

% flock ./linger ./linger 8 &
[3] 5941
% 59421598557788

% flock ./linger ./linger 9 &
[4] 5945
% flock ./linger ./linger 11 &
[5] 5946
% 59471598557796
59501598557805

[3]   Done                    flock ./linger ./linger 8
[4]   Done                    flock ./linger ./linger 9
[5]   Done                    flock ./linger ./linger 11

What you're trying to do doesn't work, because for the shell stopping a command is like it immediately exiting with a non-zero (fail) status:

% sleep 10 || echo FAIL
^Z
[3]+  Stopped                 sleep 10
FAIL
% fg
sleep 10
% echo $?
0
Source Link
user313992
user313992

If you're on a GNU/Linux system or have coreutils installed, use flock(1) (maybe using the executable/command itself as the lockfile):

% cat linger
echo -n $$; date +%s; sleep $1

% flock ./linger ./linger 8 &
[3] 5941
% 59421598557788

% flock ./linger ./linger 9 &
[4] 5945
% flock ./linger ./linger 11 &
[5] 5946
% 59471598557796
59501598557805

[3]   Done                    flock ./linger ./linger 8
[4]   Done                    flock ./linger ./linger 9
[5]   Done                    flock ./linger ./linger 11