2

I have a program, let is call it xcommand. when it is running, it has no stdout, but it writes its output to a file.

What I want to a achieve is like this: After I running xcommand, during its running I want to see its output in real time, and if I found something abnormal, I then turn off the output and at the same time, bring back xcommand.

I tried several ways, for example in the bash script I write

xcommand &
tail -f outputfile
fg

However, the problem is as soon as I press ctrl+c, the whole thing is stopped. And fg is not running at all.

So is it possible to achieve what I want?

3

When non-interactive (like in scripts), shells don't do job control. They don't put asynchronous jobs in background. Those remain in the same process group as the rest of the script, so Ctrl-C will cause a SIGINT to be sent to them as well (assuming the script itself is started in foreground).

You can issue a set -m for the shell to do job control when non-interactive:

#! /bin/bash -
set -m
xcommand & # start as a background job, so won't receive SIGINT upon ^C
tail -f outputfile # start in foreground. Will receive SIGINT.
fg # bring the xcommand job in foreground and wait for it. Will receive SIGINT

For that to work, that script has to be started in foreground. Also beware that if you press Ctrl-Z or if the background job tries to read from the terminal, you'll get into trouble.

In my experience, this kind of trick only "works" in bash or yash, generally not other Bourne-like shells.

0

If you start your program in the background with

xcommand &

pressing Ctrl+C in the shell will not stop it.

If you then do

tail -f outputfile

and press Ctrl+C, only the tail process will be terminated.

If you then do

fg

you will put xcommand in the foreground. Now, pressing Ctrl+C will terminate the xcommand process.

So, don't put the xcommand process in the foreground, or, if you do, press Ctrl+Z and follow up with bg to put it back into the background.

  • Hi, Kusalananda, I know if they run seprately, then it will work. But I want the whole process automatic. So actually I am running a script and I found myself frequently forget to bring back the xcommand and start another run – user15964 May 3 '17 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.