In my c++ program, I try to run programs in the background by simply not waiting for them.
However in Linux, if I start vi in the background like this: vi &
, then vi doesn't show up. In my program, vi will still pop up even if I don't wait for it to terminate.
So does that mean that I'm not really running it in the background? How can this be fixed?
Also, I noticed that in Linux if I type fg
to bring vi into the foreground, then vi will appear. How can I do this in c++?
What's going on here is rather complicated (for more information than you probably require, see glibc's manual section on job control) but the short version is: Only the foreground process group can access the terminal. Any other process gets automatically ^Zed by the kernel if it tries to access the terminal.
When you fork a process from C, if the parent is in the foreground process group, the child is also considered to be in the foreground process group unless either the parent or the child changes that. When you do vi &
, the shell (which is just another C program, remember) takes vi
out of the foreground process group. But you're not doing that, so vi
runs immediately.
Now, you want to fork a process from your C program and have it be treated the same as if it had been run with &
from the shell. You can only do part of that. You can put it into a non-foreground process group -- see the glibc manual for instructions; as I said, it's complicated -- but you can't add it to the list of process groups that the shell's job control commands know about. That list is state internal to the shell, there's no way to get at it from another process.