2 * \file ForkedCalls.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Angus Leeming
8 * \author Alfredo Braunstein
10 * Full author contact details are available in file CREDITS.
15 #include "support/ForkedCalls.h"
17 #include "support/debug.h"
18 #include "support/filetools.h"
19 #include "support/lstrings.h"
20 #include "support/lyxlib.h"
21 #include "support/os.h"
22 #include "support/Timeout.h"
24 #include <boost/bind.hpp>
44 # include <sys/wait.h>
45 # ifndef CXX_GLOBAL_CSTD
65 /////////////////////////////////////////////////////////////////////
69 /////////////////////////////////////////////////////////////////////
71 class Murder : public boost::signals::trackable {
74 static void killItDead(int secs, pid_t pid)
77 new Murder(secs, pid);
79 support::kill(pid, SIGKILL);
86 support::kill(pid_, SIGKILL);
87 lyxerr << "Killed " << pid_ << std::endl;
93 Murder(int secs, pid_t pid)
94 : timeout_(1000*secs, Timeout::ONETIME), pid_(pid)
96 timeout_.timeout.connect(boost::bind(&Murder::kill, this));
109 /////////////////////////////////////////////////////////////////////
113 /////////////////////////////////////////////////////////////////////
115 ForkedProcess::ForkedProcess()
116 : pid_(0), retval_(0)
120 void ForkedProcess::emitSignal()
123 signal_->operator()(pid_, retval_);
128 // Spawn the child process
129 int ForkedProcess::run(Starttype type)
132 pid_ = generateChild();
133 if (pid_ <= 0) { // child or fork failed.
140 retval_ = waitForChild();
143 // Integrate into the Controller
144 ForkedCallsController::addCall(*this);
153 bool ForkedProcess::running() const
158 #if !defined (_WIN32)
159 // Un-UNIX like, but we don't have much use for
160 // knowing if a zombie exists, so just reap it first.
162 waitpid(pid(), &waitstatus, WNOHANG);
165 // Racy of course, but it will do.
166 if (support::kill(pid(), 0) && errno == ESRCH)
172 void ForkedProcess::kill(int tol)
174 lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
176 lyxerr << "Can't kill non-existent process!" << endl;
180 int const tolerance = std::max(0, tol);
181 if (tolerance == 0) {
183 Murder::killItDead(0, pid());
185 int ret = support::kill(pid(), SIGHUP);
187 // The process is already dead if wait_for_death is false
188 bool const wait_for_death = (ret == 0 && errno != ESRCH);
191 Murder::killItDead(tolerance, pid());
196 // Wait for child process to finish. Returns returncode from child.
197 int ForkedProcess::waitForChild()
199 // We'll pretend that the child returns 1 on all error conditions.
203 HANDLE const hProcess = HANDLE(pid_);
205 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
207 switch (wait_status) {
208 case WAIT_OBJECT_0: {
210 if (!GetExitCodeProcess(hProcess, &exit_code)) {
211 lyxerr << "GetExitCodeProcess failed waiting for child\n"
212 << getChildErrorMessage() << std::endl;
218 lyxerr << "WaitForSingleObject failed waiting for child\n"
219 << getChildErrorMessage() << std::endl;
227 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
228 if (waitrpid == -1) {
229 lyxerr << "LyX: Error waiting for child:"
230 << strerror(errno) << endl;
232 } else if (WIFEXITED(status)) {
233 // Child exited normally. Update return value.
234 retval_ = WEXITSTATUS(status);
236 } else if (WIFSIGNALED(status)) {
237 lyxerr << "LyX: Child didn't catch signal "
239 << "and died. Too bad." << endl;
241 } else if (WIFSTOPPED(status)) {
242 lyxerr << "LyX: Child (pid: " << pid_
243 << ") stopped on signal "
245 << ". Waiting for child to finish." << endl;
247 lyxerr << "LyX: Something rotten happened while "
248 "waiting for child " << pid_ << endl;
257 /////////////////////////////////////////////////////////////////////
261 /////////////////////////////////////////////////////////////////////
264 int ForkedCall::startScript(Starttype wait, string const & what)
267 retval_ = startScript(what, SignalTypePtr());
277 int ForkedCall::startScript(string const & what, SignalTypePtr signal)
282 return run(DontWait);
286 // generate child in background
287 int ForkedCall::generateChild()
289 string line = trim(command_);
293 // Split the input command up into an array of words stored
294 // in a contiguous block of memory. The array contains pointers
296 // Don't forget the terminating `\0' character.
297 char const * const c_str = line.c_str();
298 vector<char> vec(c_str, c_str + line.size() + 1);
300 // Splitting the command up into an array of words means replacing
301 // the whitespace between words with '\0'. Life is complicated
302 // however, because words protected by quotes can contain whitespace.
304 // The strategy we adopt is:
305 // 1. If we're not inside quotes, then replace white space with '\0'.
306 // 2. If we are inside quotes, then don't replace the white space
307 // but do remove the quotes themselves. We do this naively by
308 // replacing the quote with '\0' which is fine if quotes
309 // delimit the entire word.
310 char inside_quote = 0;
311 vector<char>::iterator it = vec.begin();
312 vector<char>::iterator const end = vec.end();
313 for (; it != end; ++it) {
318 else if (c == '\'' || c == '"') {
321 // spawnvp *requires* the quotes or it will
322 // split the arg at the internal whitespace!
323 // Make shure the quote is a DOS-style one.
330 } else if (c == inside_quote) {
340 // Build an array of pointers to each word.
344 for (; it != end; ++it) {
345 if (*it != '\0' && prev == '\0')
346 argv.push_back(&*it);
352 if (lyxerr.debugging(Debug::FILES)) {
353 vector<char *>::iterator ait = argv.begin();
354 vector<char *>::iterator const aend = argv.end();
355 lyxerr << "<command>\n\t" << line
356 << "\n\tInterpretted as:\n\n";
357 for (; ait != aend; ++ait)
359 lyxerr << '\t'<< *ait << '\n';
360 lyxerr << "</command>" << std::endl;
364 pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
366 pid_t const cpid = ::fork();
369 execvp(argv[0], &*argv.begin());
371 // If something goes wrong, we end up here
372 lyxerr << "execvp of \"" << command_ << "\" failed: "
373 << strerror(errno) << endl;
380 lyxerr << "Could not fork: " << strerror(errno) << endl;
387 /////////////////////////////////////////////////////////////////////
391 /////////////////////////////////////////////////////////////////////
393 namespace ForkedCallQueue {
395 /// A process in the queue
396 typedef std::pair<std::string, ForkedCall::SignalTypePtr> Process;
397 /** Add a process to the queue. Processes are forked sequentially
398 * only one is running at a time.
399 * Connect to the returned signal and you'll be informed when
400 * the process has ended.
402 ForkedCall::SignalTypePtr add(std::string const & process);
404 /// in-progress queue
405 static std::queue<Process> callQueue_;
407 /// flag whether queue is running
408 static bool running_ = 0;
415 void callback(pid_t, int);
417 ForkedCall::SignalTypePtr add(string const & process)
419 ForkedCall::SignalTypePtr ptr;
420 ptr.reset(new ForkedCall::SignalType);
421 callQueue_.push(Process(process, ptr));
430 if (callQueue_.empty())
432 Process pro = callQueue_.front();
434 // Bind our chain caller
435 pro.second->connect(boost::bind(&ForkedCallQueue::callback, _1, _2));
437 // If we fail to fork the process, then emit the signal
438 // to tell the outside world that it failed.
439 if (call.startScript(pro.first, pro.second) > 0)
440 pro.second->operator()(0,1);
444 void callback(pid_t, int)
446 if (callQueue_.empty())
455 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
464 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
473 } // namespace ForkedCallsQueue
477 /////////////////////////////////////////////////////////////////////
479 // ForkedCallsController
481 /////////////////////////////////////////////////////////////////////
484 string const getChildErrorMessage()
486 DWORD const error_code = ::GetLastError();
488 HLOCAL t_message = 0;
489 bool const ok = ::FormatMessage(
490 FORMAT_MESSAGE_ALLOCATE_BUFFER |
491 FORMAT_MESSAGE_FROM_SYSTEM,
493 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
494 (LPTSTR) &t_message, 0, 0
497 std::ostringstream ss;
498 ss << "LyX: Error waiting for child: " << error_code;
501 ss << ": " << (LPTSTR)t_message;
502 ::LocalFree(t_message);
504 ss << ": Error unknown.";
511 namespace ForkedCallsController {
513 typedef boost::shared_ptr<ForkedProcess> ForkedProcessPtr;
514 typedef std::list<ForkedProcessPtr> ListType;
515 typedef ListType::iterator iterator;
518 /// The child processes
519 static ListType forkedCalls;
521 iterator find_pid(pid_t pid)
523 return find_if(forkedCalls.begin(), forkedCalls.end(),
524 bind(equal_to<pid_t>(),
525 bind(&ForkedCall::pid, _1),
530 void addCall(ForkedProcess const & newcall)
532 forkedCalls.push_back(newcall.clone());
536 // Check the list of dead children and emit any associated signals.
537 void handleCompletedProcesses()
539 ListType::iterator it = forkedCalls.begin();
540 ListType::iterator end = forkedCalls.end();
542 ForkedProcessPtr actCall = *it;
543 bool remove_it = false;
546 HANDLE const hProcess = HANDLE(actCall->pid());
548 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
550 switch (wait_status) {
554 case WAIT_OBJECT_0: {
556 if (!GetExitCodeProcess(hProcess, &exit_code)) {
557 lyxerr << "GetExitCodeProcess failed waiting for child\n"
558 << getChildErrorMessage() << std::endl;
559 // Child died, so pretend it returned 1
560 actCall->setRetValue(1);
562 actCall->setRetValue(exit_code);
568 lyxerr << "WaitForSingleObject failed waiting for child\n"
569 << getChildErrorMessage() << std::endl;
570 actCall->setRetValue(1);
575 pid_t pid = actCall->pid();
577 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
579 if (waitrpid == -1) {
580 lyxerr << "LyX: Error waiting for child: "
581 << strerror(errno) << endl;
583 // Child died, so pretend it returned 1
584 actCall->setRetValue(1);
587 } else if (waitrpid == 0) {
588 // Still running. Move on to the next child.
590 } else if (WIFEXITED(stat_loc)) {
591 // Ok, the return value goes into retval.
592 actCall->setRetValue(WEXITSTATUS(stat_loc));
595 } else if (WIFSIGNALED(stat_loc)) {
596 // Child died, so pretend it returned 1
597 actCall->setRetValue(1);
600 } else if (WIFSTOPPED(stat_loc)) {
601 lyxerr << "LyX: Child (pid: " << pid
602 << ") stopped on signal "
603 << WSTOPSIG(stat_loc)
604 << ". Waiting for child to finish." << endl;
607 lyxerr << "LyX: Something rotten happened while "
608 "waiting for child " << pid << endl;
610 // Child died, so pretend it returned 1
611 actCall->setRetValue(1);
617 forkedCalls.erase(it);
618 actCall->emitSignal();
620 /* start all over: emiting the signal can result
621 * in changing the list (Ab)
623 it = forkedCalls.begin();
631 // Kill the process prematurely and remove it from the list
632 // within tolerance secs
633 void kill(pid_t pid, int tolerance)
635 ListType::iterator it = find_pid(pid);
636 if (it == forkedCalls.end())
639 (*it)->kill(tolerance);
640 forkedCalls.erase(it);
643 } // namespace ForkedCallsController
645 } // namespace support