From dcf9c5a0fc293518887ddc9ec459a4fc09375ddb Mon Sep 17 00:00:00 2001 From: Jari Sundell Date: Sun, 9 Oct 2011 19:23:30 +0900 Subject: [PATCH] Properly detach from background process. --- src/rpc/exec_file.cc | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/rpc/exec_file.cc b/src/rpc/exec_file.cc index bc9fe410..64565c8e 100644 --- a/src/rpc/exec_file.cc +++ b/src/rpc/exec_file.cc @@ -79,6 +79,23 @@ ExecFile::execute(const char* file, char* const* argv, int flags) { throw torrent::input_error("ExecFile::execute(...) Fork failed."); if (childPid == 0) { + if (flags & flag_background) { + pid_t detached_pid = fork(); + + if (detached_pid == -1) + _exit(-1); + + if (detached_pid != 0) { + if (m_logFd != -1) + write(m_logFd, "\n--- Background task ---\n", sizeof("\n--- Background task ---\n")); + + _exit(0); + } + + m_logFd = -1; + flags &= ~flag_capture; + } + int devNull = open("/dev/null", O_RDWR); if (devNull != -1) dup2(devNull, 0); @@ -110,13 +127,6 @@ ExecFile::execute(const char* file, char* const* argv, int flags) { _exit(result); } - if (flags & flag_background) { - if (m_logFd != -1) - write(m_logFd, "\n--- Background task ---\n", sizeof("\n--- Background task ---\n")); - - return 0; - } - // We yield the global lock when waiting for the executed command to // finish so that XMLRPC and other threads can continue working. ThreadBase::release_global_lock();