How can a C/C++ program put itself into background? How can a C/C++ program put itself into background? shell shell

How can a C/C++ program put itself into background?


My advice: don't do this, at least not under Linux/UNIX.

GUI programs under Linux/UNIX traditionally do not auto-background themselves. While this may occasionally be annoying to newbies, it has a number of advantages:

  • Makes it easy to capture standard error in case of core dumps / other problems that need debugging.

  • Makes it easy for a shell script to run the program and wait until it's completed.

  • Makes it easy for a shell script to run the program in the background and get its process id:

    gui-program &pid=$!# do something with $pid later, such as check if the program is still running

    If your program forks itself, this behavior will break.

"Scriptability" is useful in so many unexpected circumstances, even with GUI programs, that I would hesitate to explicitly break these behaviors.

Windows is another story. AFAIK, Windows programs automatically run in the background--even when invoked from a command shell--unless they explicitly request access to the command window.


On Linux, daemon() is what you're looking for, if I understand you correctly.


The way it's typically done on Unix-like OSes is to fork() at the beginning and exit from the parent. This won't work on Windows, but is much more elegant than launching another process where forking exists.