How can I capture the output of a background process

What's the best way to run a process in the background and only get its output when needed?

Intended Usage: Outputting a prompt script with large initialization is initialized once per session, not every time the run is started. Note: Two-way communication is required: The shell must indicate when a new prompt is required, what is the last command status.

Known solutions:

  • some explicitly generated files on the filesystem (FIFO files, UNIX sockets): It would be better to avoid this as it means I have to choose a filename, make sure it is garbage collected on the output and add something to clean up more files used in case of failure.
  • Zsh / zpty module: It looks a bit like an overload for this job and doesn't work in bash.
  • coprocesses: doesn't work in bash and AFAIK only one coprocess per session is allowed.
+3


source to share


1 answer


Bash supports sinces 4.0 coprocesses, but multiple coprocesses are still experimental.

I would go with some explicitly generated files, naming them ~/.myThing-$HOSTNAME/fifo

if they are for user and host. You can use flock

to determine relatively easily whether a command is still running and running:

(
  flock -n 123 || exit 1
  rm/mkfifo ..
  exec yourServer < .. > ..
) 123> ~/".myThing-$HOSTNAME/lockfile"

      



If a command or server dies, the lock is automatically released and you only have a few zero-length files. The next time the server starts up, it will uninstall and reinstall them.

The server request will be the same, but exit if not blocking is used (and, if necessary, waiting blocking to avoid contention).

+1


source







All Articles