3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
8 * Interface cleaned up by
9 * \author Angus Leeming
11 * Full author contact details are available in file CREDITS.
13 * An instance of Class Forkedcall represents a single child process.
15 * Class Forkedcall uses fork() and execvp() to lauch the child process.
17 * Once launched, control is returned immediately to the parent process
18 * but a Signal can be emitted upon completion of the child.
20 * The child process is not killed when the Forkedcall instance goes out of
21 * scope, but it can be killed by an explicit invocation of the kill() member
27 #include "support/forkedcall.h"
28 #include "support/forkedcontr.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
31 #include "support/filetools.h"
32 #include "support/os.h"
36 #include "frontends/Timeout.h"
38 #include <boost/bind.hpp>
53 # include <sys/types.h>
54 # include <sys/wait.h>
61 #ifndef CXX_GLOBAL_CSTD
71 class Murder : public boost::signals::trackable {
74 static void killItDead(int secs, pid_t pid)
77 new Murder(secs, pid);
78 } else if (pid != 0) {
79 lyx::support::kill(pid, SIGKILL);
87 lyx::support::kill(pid_, SIGKILL);
89 lyxerr << "Killed " << pid_ << std::endl;
95 Murder(int secs, pid_t pid)
96 : timeout_(0), pid_(pid)
98 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
99 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
117 ForkedProcess::ForkedProcess()
118 : pid_(0), retval_(0)
122 void ForkedProcess::emitSignal()
125 signal_->operator()(pid_, retval_);
130 // Spawn the child process
131 int ForkedProcess::run(Starttype type)
134 pid_ = generateChild();
135 if (pid_ <= 0) { // child or fork failed.
142 retval_ = waitForChild();
145 // Integrate into the Controller
146 ForkedcallsController & contr = ForkedcallsController::get();
147 contr.addCall(*this);
156 bool ForkedProcess::running() const
161 #if !defined (_WIN32)
162 // Un-UNIX like, but we don't have much use for
163 // knowing if a zombie exists, so just reap it first.
165 waitpid(pid(), &waitstatus, WNOHANG);
168 // Racy of course, but it will do.
169 if (lyx::support::kill(pid(), 0) && errno == ESRCH)
175 void ForkedProcess::kill(int tol)
177 lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
179 lyxerr << "Can't kill non-existent process!" << endl;
183 int const tolerance = std::max(0, tol);
184 if (tolerance == 0) {
186 Murder::killItDead(0, pid());
189 int ret = lyx::support::kill(pid(), SIGHUP);
191 // The process is already dead if wait_for_death is false
192 bool const wait_for_death = (ret == 0 && errno != ESRCH);
194 if (wait_for_death) {
195 Murder::killItDead(tolerance, pid());
201 // Wait for child process to finish. Returns returncode from child.
202 int ForkedProcess::waitForChild()
204 // We'll pretend that the child returns 1 on all error conditions.
208 HANDLE const hProcess = HANDLE(pid_);
210 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
212 switch (wait_status) {
213 case WAIT_OBJECT_0: {
215 if (!GetExitCodeProcess(hProcess, &exit_code)) {
216 lyxerr << "GetExitCodeProcess failed waiting for child\n"
217 << getChildErrorMessage() << std::endl;
223 lyxerr << "WaitForSingleObject failed waiting for child\n"
224 << getChildErrorMessage() << std::endl;
232 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
233 if (waitrpid == -1) {
234 lyxerr << "LyX: Error waiting for child:"
235 << strerror(errno) << endl;
237 } else if (WIFEXITED(status)) {
238 // Child exited normally. Update return value.
239 retval_ = WEXITSTATUS(status);
241 } else if (WIFSIGNALED(status)) {
242 lyxerr << "LyX: Child didn't catch signal "
244 << "and died. Too bad." << endl;
246 } else if (WIFSTOPPED(status)) {
247 lyxerr << "LyX: Child (pid: " << pid_
248 << ") stopped on signal "
250 << ". Waiting for child to finish." << endl;
252 lyxerr << "LyX: Something rotten happened while "
253 "waiting for child " << pid_ << endl;
262 int Forkedcall::startscript(Starttype wait, string const & what)
265 retval_ = startscript(what, SignalTypePtr());
275 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
280 return run(DontWait);
284 // generate child in background
285 int Forkedcall::generateChild()
287 string line = trim(command_);
291 // Split the input command up into an array of words stored
292 // in a contiguous block of memory. The array contains pointers
294 // Don't forget the terminating `\0' character.
295 char const * const c_str = line.c_str();
296 vector<char> vec(c_str, c_str + line.size() + 1);
298 // Splitting the command up into an array of words means replacing
299 // the whitespace between words with '\0'. Life is complicated
300 // however, because words protected by quotes can contain whitespace.
302 // The strategy we adopt is:
303 // 1. If we're not inside quotes, then replace white space with '\0'.
304 // 2. If we are inside quotes, then don't replace the white space
305 // but do remove the quotes themselves. We do this naively by
306 // replacing the quote with '\0' which is fine if quotes
307 // delimit the entire word.
308 char inside_quote = 0;
309 vector<char>::iterator it = vec.begin();
310 vector<char>::iterator const end = vec.end();
311 for (; it != end; ++it) {
316 else if (c == '\'' || c == '"') {
319 // spawnvp *requires* the quotes or it will
320 // split the arg at the internal whitespace!
321 // Make shure the quote is a DOS-style one.
328 } else if (c == inside_quote) {
338 // Build an array of pointers to each word.
342 for (; it != end; ++it) {
343 if (*it != '\0' && prev == '\0')
344 argv.push_back(&*it);
350 if (lyxerr.debugging(Debug::FILES)) {
351 vector<char *>::iterator ait = argv.begin();
352 vector<char *>::iterator const aend = argv.end();
353 lyxerr << "<command>\n\t" << line
354 << "\n\tInterpretted as:\n\n";
355 for (; ait != aend; ++ait)
357 lyxerr << '\t'<< *ait << '\n';
358 lyxerr << "</command>" << std::endl;
361 #if defined (__EMX__)
362 pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
363 argv[0], &*argv.begin());
364 #elif defined (_WIN32)
365 pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
367 pid_t const cpid = ::fork();
370 execvp(argv[0], &*argv.begin());
372 // If something goes wrong, we end up here
373 lyxerr << "execvp of \"" << command_ << "\" failed: "
374 << strerror(errno) << endl;
381 lyxerr << "Could not fork: " << strerror(errno) << endl;
387 } // namespace support