From foreground to background.


Sometimes you start a task from a console, let it run for a while, and then realize you should have been doing it in background. A typical example of that, is launching x11vnc from a ssh shell, connecting to the remote vnc-server via vncviewer, and then closing the ssh shell; that of course would terminate all children tasks, including x11vnc, even if (and I don’t know why, actually) you launched them with the “&” appended (this usually puts the issued command in background execution). To avoid early termination, you could simply minimize the console window, and forget it. But we are nerds. We never forget.

So.. what’s the clean way of closing a console without terminating the running process? I use this sequence:

  1. open the console (and connect to remote server via ssh);
  2. issue any long-running not-interactive command (e.g.: gzip, cat, dd, sort, nmap, hydra, …) in the regular way;
  3. let it run for a while (1-2 sec.), just to be sure it started correctly;
  4. type: <Ctrl>+Z
  5. this will temporarily stop/freeze the task, getting you back to the prompt;
  6. issue this command: bg
  7. this will put the [last] stopped job in background execution, getting you back to the prompt (while the command stdin is released, you may notice that its stdout is still bound to the console, so you may get notifications every while and then, messing your command line: nevermind, even if you can’t tell what is what, the computer knows, and doesn’t mix you input with stdout);
  8. type <Enter> a couple of times (just to be sure you got the prompt).
  9. type: <Ctrl>+D
  10. this will close the console session (but NOT the background tasks).

Ok, you’re done… but wait! You just realize something went wrong, and you need the task to get back in foreground! Nevermind: just type the opposite command: fg

This will revert the (last) bg task to fg, so that your console can finally write to the task stdin.

If you extensively use bg, you may be finding yourself lost in a mess of bg tasks: how to tell what is still running, and what is done? The answer is this command: jobs

This will list all (past & current) bg tasks in an sorted list: use the item position number (e.g.: n) to get the task back in fg (e.g.: fg %n) or to kill it (e.g.: kill %n). Please notice that, if you miss the leading percent char (%), the number (n) will be parsed as a PID (=process-id, not job-id), with undesirable results (e.g.: killing the wrong task).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: