/* bg.cc - send process to the background
 * Copyright 2005 Bas Wijnen <wijnen@debian.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include "bg.hh"
#include "debug.hh"
#include "error.hh"

namespace shevek
{
  void bg (bool exit_on_fail)
  {
    startfunc;
    char *debug = std::getenv ("SHEVEK_DEBUG");
    if (debug && (std::string (":") + debug + ":").find (":bg:")
		    != std::string::npos)
      {
	std::cerr << "shevek::bg called, but not backgrounding because "
		"bg is set in SHEVEK_DEBUG\n";
	return;
      }
    switch (fork () )
    {
    case -1:
      if (exit_on_fail)
	{
	  shevek_error_errno ("unable to fork");
	  exit (1);
	}
      shevek_warning_errno ("unable to fork, remaining in foreground");
      return;
    case 0: // child
      return;
    default: // parent
      exit (0);
    }
  }
}
