title: How can a C/C++ program put itself into background?
body: <p>What's the best way for a running C or C++ program that's been launched from the command line to put itself into the background, equivalent to if the user had launched from the unix shell with '&amp;' at the end of the command?  (But the user didn't.)  It's a GUI app and doesn't need any shell I/O, so there's no reason to tie up the shell after launch.  But I want a shell command launch to be auto-backgrounded without the '&amp;' (or on Windows).</p>
  
  <p>Ideally, I want a solution that would work on any of Linux, OS X, and Windows.  (Or separate solutions that I can select with #ifdef.)  It's ok to assume that this should be done right at the beginning of execution, as opposed to somewhere in the middle.</p>
  
  <p>One solution is to have the main program be a script that launches the real binary, carefully putting it into the background.  But it seems unsatisfying to need these coupled shell/binary pairs.</p>
  
  <p>Another solution is to immediately launch <em>another</em> executed version (with 'system' or CreateProcess), with the same command line arguments, but putting the child in the background and then having the parent exit.  But this seems clunky compared to the process putting <em>itself</em> into background.</p>
  
  <p><strong>Edited after a few answers</strong>:  Yes, a fork() (or system(), or CreateProcess on Windows) is one way to sort of do this, that I hinted at in my original question.  But all of these solutions make a SECOND process that is backgrounded, and then terminate the original process.  I was wondering if there was a way to put the EXISTING process into the background.  One difference is that if the app was launched from a script that recorded its process id (perhaps for later killing or other purpose), the newly forked or created process will have a different id and so will not be controllable by any launching script, if you see what I'm getting at.</p>
  
  <p><strong>Edit #2</strong>: </p>
  
  <p>fork() isn't a good solution for OS X, where the man page for 'fork' says that it's unsafe if certain frameworks or libraries are being used.  I tried it, and my app complains loudly at runtime: "The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec()."  </p>
  
  <p>I was intrigued by daemon(), but when I tried it on OS X, it gave the same error message, so I assume that it's just a fancy wrapper for fork() and has the same restrictions.</p>
  
  <p>Excuse the OS X centrism, it just happens to be the system in front of me at the moment.  But I am indeed looking for a solution to all three platforms.</p>