Kitz Forum

Computer Software => Linux => Topic started by: Weaver on October 16, 2018, 09:29:10 PM

Title: Running two things in the background
Post by: Weaver on October 16, 2018, 09:29:10 PM
What I would like to do is run several things in the background, and capturing the output of each in a safe way. Needs to be safe in case if reentrancy, in case the tool ever getting run twice simultaneously, a problem which I presume could easily be dealt with by decorating things with the current pid. The thing I have no idea about is how to wait on all of some sub processes, need to wait until all of them have completed.

(The WinNT API has nice calls to do exactly this kind of thing, waiting on a number of asynchronous events of all types, such as timers, mouse and keyboard events, resumabke events related to processes too I suppose. All fine if you are writing stuff in C say, But I never managed to solve this problem with NT batch files nor Powershell scripts as my knowledge did not stretch far enough and MS never bothered to put anything nice and easy for such a thing into their shells. They have the start and start /wait commands but if you did a ‘start’ there was no way that I knew to get an event telling you the process had finished.)
Title: Re: Running two things in the background
Post by: dee.jay on October 17, 2018, 09:02:15 AM
You could probably do this with "screen" that lets you create like, a virtual screen you can "attach" and "detach"

So, if you wish to spin up some new task, one would invoke Screen, start the task, then detach that screen.

You could then of course re-attach back to that output later.
Title: Re: Running two things in the background
Post by: Weaver on October 17, 2018, 05:27:54 PM
I have not tested it yet, but I did manage to find something by googling eventually. It is a trick that involves the abuse of ‘tail’

Code: [Select]

    tail --pid=$pid -f /dev/null


Will report back when I have tried it.
Title: Re: Running two things in the background
Post by: petef on October 26, 2018, 04:48:43 PM
If that does not work out you could try using other file descriptors. Most people are familiar with 1 for stdout and 2 for stderr but you can redirect to other numbers to do more complex redirection.

https://www.tldp.org/LDP/abs/html/io-redirection.html

By default a simple wait with no arguments waits for all background processes. It can also wait for a job number (e.g. %1) or child process ID.

https://www.tldp.org/LDP/abs/html/x9644.html
Title: Re: Running two things in the background
Post by: Weaver on November 09, 2018, 01:45:36 AM
I found the answer - the ‘jobs’ and ‘wait’ commands are what I needed. With these commands, you can identify the background processes that you started using a ‘&’ command suffix, and wait can be used to wait they have all completed. I haven’t really tested it very thoroughly but it seems to do the right thing.