Close the pipe even if the subprocesses of the first command are still running in the background

Suppose I have test.sh as shown below. The goal is to run some background tasks with this script, which constantly updates some files. If for some reason the background task is terminated, it should be started again.

 #!/bin/sh if [ -f pidfile ] && kill -0 $(cat pidfile); then cat somewhere exit fi while true; do echo "something" >> somewhere sleep 1 done & echo $! > pidfile 

and want to call it as ./test.sh | otherprogram ./test.sh | otherprogram , e. g ./test.sh | cat ./test.sh | cat .

The pipe does not close because the background process still exists and may lead to some exit. How can I say that the pipe closes at the end of test.sh ? Is there a better way than checking for the existence of a pidfile before calling the pipe command?

As an option, I tried using #!/bin/bash and disown at the end of test.sh , but it is still waiting for the channel to close.


What I'm actually trying to achieve: I have a β€œstatus” script that collects the output of various scripts ( uptime , free , date , get-xy-from-dbus , etc.), similar to test.sh here. The output script file is transferred to my window manager, which displays it. It is also used on the bottom line of the GNU screen.

Since some of the scripts that are used may take some time to create output, I want to separate them from the output assembly. So I put them in a while true; do script; sleep 1; done while true; do script; sleep 1; done while true; do script; sleep 1; done , which starts if it is not already running.

Now the problem is that I don’t know how to tell the calling script to "really" separate the daemon process.

+4
source share
3 answers

Make sure this serves your purpose: (I assume you are not interested in any stderr commands in the while loop. You would edit the code if you have one. :-))

 #!/bin/bash if [ -f pidfile ] && kill -0 $(cat pidfile); then cat somewhere exit fi while true; do echo "something" >> somewhere sleep 1 done >/dev/null 2>&1 & echo $! > pidfile 
+3
source

If you want to explicitly close the file descriptor, for example, for example 1, which is the standard output, you can do this with

 exec 1<&- 

This is true for POSIX shells, see here .

+1
source

When you put a while loop in an explicit subshell and run a subshell in the background, this will give the desired behavior.

 (while true; do echo "something" >> somewhere sleep 1 done)& 
0
source

Source: https://habr.com/ru/post/1437365/


All Articles