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 "support/bind.h"
44 # include <sys/wait.h>
56 /////////////////////////////////////////////////////////////////////
60 /////////////////////////////////////////////////////////////////////
62 class Murder : public boost::signals::trackable {
65 static void killItDead(int secs, pid_t pid)
68 new Murder(secs, pid);
70 support::kill(pid, SIGKILL);
77 support::kill(pid_, SIGKILL);
78 lyxerr << "Killed " << pid_ << endl;
84 Murder(int secs, pid_t pid)
85 : timeout_(1000*secs, Timeout::ONETIME), pid_(pid)
87 timeout_.timeout.connect(lyx::bind(&Murder::kill, this));
100 /////////////////////////////////////////////////////////////////////
104 /////////////////////////////////////////////////////////////////////
106 ForkedProcess::ForkedProcess()
107 : pid_(0), retval_(0)
111 bool ForkedProcess::IAmAChild = false;
114 void ForkedProcess::emitSignal()
117 signal_->operator()(pid_, retval_);
122 // Spawn the child process
123 int ForkedProcess::run(Starttype type)
126 pid_ = generateChild();
127 if (pid_ <= 0) { // child or fork failed.
130 //we also do this in fork(), too, but maybe someone will try
138 retval_ = waitForChild();
141 // Integrate into the Controller
142 ForkedCallsController::addCall(*this);
151 bool ForkedProcess::running() const
156 #if !defined (_WIN32)
157 // Un-UNIX like, but we don't have much use for
158 // knowing if a zombie exists, so just reap it first.
160 waitpid(pid(), &waitstatus, WNOHANG);
163 // Racy of course, but it will do.
164 if (support::kill(pid(), 0) && errno == ESRCH)
170 void ForkedProcess::kill(int tol)
172 lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
174 lyxerr << "Can't kill non-existent process!" << endl;
178 int const tolerance = max(0, tol);
179 if (tolerance == 0) {
181 Murder::killItDead(0, pid());
183 int ret = support::kill(pid(), SIGHUP);
185 // The process is already dead if wait_for_death is false
186 bool const wait_for_death = (ret == 0 && errno != ESRCH);
189 Murder::killItDead(tolerance, pid());
194 pid_t ForkedProcess::fork() {
195 #if !defined (HAVE_FORK)
198 pid_t pid = ::fork();
206 // Wait for child process to finish. Returns returncode from child.
207 int ForkedProcess::waitForChild()
209 // We'll pretend that the child returns 1 on all error conditions.
213 HANDLE const hProcess = HANDLE(pid_);
215 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
217 switch (wait_status) {
218 case WAIT_OBJECT_0: {
220 if (!GetExitCodeProcess(hProcess, &exit_code)) {
221 lyxerr << "GetExitCodeProcess failed waiting for child\n"
222 << getChildErrorMessage() << endl;
228 lyxerr << "WaitForSingleObject failed waiting for child\n"
229 << getChildErrorMessage() << endl;
237 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
238 if (waitrpid == -1) {
239 lyxerr << "LyX: Error waiting for child:"
240 << strerror(errno) << endl;
242 } else if (WIFEXITED(status)) {
243 // Child exited normally. Update return value.
244 retval_ = WEXITSTATUS(status);
246 } else if (WIFSIGNALED(status)) {
247 lyxerr << "LyX: Child didn't catch signal "
249 << "and died. Too bad." << endl;
251 } else if (WIFSTOPPED(status)) {
252 lyxerr << "LyX: Child (pid: " << pid_
253 << ") stopped on signal "
255 << ". Waiting for child to finish." << endl;
257 lyxerr << "LyX: Something rotten happened while "
258 "waiting for child " << pid_ << endl;
267 /////////////////////////////////////////////////////////////////////
271 /////////////////////////////////////////////////////////////////////
274 int ForkedCall::startScript(Starttype wait, string const & what)
277 retval_ = startScript(what, SignalTypePtr());
287 int ForkedCall::startScript(string const & what, SignalTypePtr signal)
292 return run(DontWait);
296 // generate child in background
297 int ForkedCall::generateChild()
299 string line = trim(command_);
303 #if !defined (_WIN32)
306 // Split the input command up into an array of words stored
307 // in a contiguous block of memory. The array contains pointers
309 // Don't forget the terminating `\0' character.
310 char const * const c_str = line.c_str();
311 vector<char> vec(c_str, c_str + line.size() + 1);
313 // Splitting the command up into an array of words means replacing
314 // the whitespace between words with '\0'. Life is complicated
315 // however, because words protected by quotes can contain whitespace.
317 // The strategy we adopt is:
318 // 1. If we're not inside quotes, then replace white space with '\0'.
319 // 2. If we are inside quotes, then don't replace the white space
320 // but do remove the quotes themselves. We do this naively by
321 // replacing the quote with '\0' which is fine if quotes
322 // delimit the entire word.
323 char inside_quote = 0;
324 vector<char>::iterator it = vec.begin();
325 vector<char>::iterator const end = vec.end();
326 for (; it != end; ++it) {
331 else if (c == '\'' || c == '"') {
335 } else if (c == inside_quote) {
341 // Build an array of pointers to each word.
345 for (; it != end; ++it) {
346 if (*it != '\0' && prev == '\0')
347 argv.push_back(&*it);
353 if (lyxerr.debugging(Debug::FILES)) {
354 vector<char *>::iterator ait = argv.begin();
355 vector<char *>::iterator const aend = argv.end();
356 lyxerr << "<command>\n\t" << line
357 << "\n\tInterpretted as:\n\n";
358 for (; ait != aend; ++ait)
360 lyxerr << '\t'<< *ait << '\n';
361 lyxerr << "</command>" << endl;
364 pid_t const cpid = ::fork();
367 execvp(argv[0], &*argv.begin());
369 // If something goes wrong, we end up here
370 lyxerr << "execvp of \"" << command_ << "\" failed: "
371 << strerror(errno) << endl;
380 PROCESS_INFORMATION process;
382 memset(&startup, 0, sizeof(STARTUPINFO));
383 memset(&process, 0, sizeof(PROCESS_INFORMATION));
385 startup.cb = sizeof(STARTUPINFO);
387 if (CreateProcess(0, (LPSTR)line.c_str(), 0, 0, FALSE,
388 CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
389 CloseHandle(process.hThread);
390 cpid = (pid_t)process.hProcess;
396 lyxerr << "Could not fork: " << strerror(errno) << endl;
403 /////////////////////////////////////////////////////////////////////
407 /////////////////////////////////////////////////////////////////////
409 namespace ForkedCallQueue {
411 /// A process in the queue
412 typedef pair<string, ForkedCall::SignalTypePtr> Process;
413 /** Add a process to the queue. Processes are forked sequentially
414 * only one is running at a time.
415 * Connect to the returned signal and you'll be informed when
416 * the process has ended.
418 ForkedCall::SignalTypePtr add(string const & process);
420 /// in-progress queue
421 static queue<Process> callQueue_;
423 /// flag whether queue is running
424 static bool running_ = 0;
431 void callback(pid_t, int);
433 ForkedCall::SignalTypePtr add(string const & process)
435 ForkedCall::SignalTypePtr ptr;
436 ptr.reset(new ForkedCall::SignalType);
437 callQueue_.push(Process(process, ptr));
446 if (callQueue_.empty())
448 Process pro = callQueue_.front();
450 // Bind our chain caller
451 pro.second->connect(lyx::bind(&ForkedCallQueue::callback, _1, _2));
453 //If we fail to fork the process, then emit the signal
454 //to tell the outside world that it failed.
455 if (call.startScript(pro.first, pro.second) > 0)
456 pro.second->operator()(0,1);
460 void callback(pid_t, int)
462 if (callQueue_.empty())
471 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
480 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
489 } // namespace ForkedCallsQueue
493 /////////////////////////////////////////////////////////////////////
495 // ForkedCallsController
497 /////////////////////////////////////////////////////////////////////
500 string const getChildErrorMessage()
502 DWORD const error_code = ::GetLastError();
504 HLOCAL t_message = 0;
505 bool const ok = ::FormatMessage(
506 FORMAT_MESSAGE_ALLOCATE_BUFFER |
507 FORMAT_MESSAGE_FROM_SYSTEM,
509 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
510 (LPTSTR) &t_message, 0, 0
514 ss << "LyX: Error waiting for child: " << error_code;
517 ss << ": " << (LPTSTR)t_message;
518 ::LocalFree(t_message);
520 ss << ": Error unknown.";
527 namespace ForkedCallsController {
529 typedef shared_ptr<ForkedProcess> ForkedProcessPtr;
530 typedef list<ForkedProcessPtr> ListType;
531 typedef ListType::iterator iterator;
534 /// The child processes
535 static ListType forkedCalls;
537 iterator find_pid(pid_t pid)
539 return find_if(forkedCalls.begin(), forkedCalls.end(),
540 lyx::bind(equal_to<pid_t>(),
541 lyx::bind(&ForkedCall::pid, _1),
546 void addCall(ForkedProcess const & newcall)
548 forkedCalls.push_back(newcall.clone());
552 // Check the list of dead children and emit any associated signals.
553 void handleCompletedProcesses()
555 ListType::iterator it = forkedCalls.begin();
556 ListType::iterator end = forkedCalls.end();
558 ForkedProcessPtr actCall = *it;
559 bool remove_it = false;
562 HANDLE const hProcess = HANDLE(actCall->pid());
564 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
566 switch (wait_status) {
570 case WAIT_OBJECT_0: {
572 if (!GetExitCodeProcess(hProcess, &exit_code)) {
573 lyxerr << "GetExitCodeProcess failed waiting for child\n"
574 << getChildErrorMessage() << endl;
575 // Child died, so pretend it returned 1
576 actCall->setRetValue(1);
578 actCall->setRetValue(exit_code);
580 CloseHandle(hProcess);
585 lyxerr << "WaitForSingleObject failed waiting for child\n"
586 << getChildErrorMessage() << endl;
587 actCall->setRetValue(1);
588 CloseHandle(hProcess);
593 pid_t pid = actCall->pid();
595 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
597 if (waitrpid == -1) {
598 lyxerr << "LyX: Error waiting for child: "
599 << strerror(errno) << endl;
601 // Child died, so pretend it returned 1
602 actCall->setRetValue(1);
605 } else if (waitrpid == 0) {
606 // Still running. Move on to the next child.
608 } else if (WIFEXITED(stat_loc)) {
609 // Ok, the return value goes into retval.
610 actCall->setRetValue(WEXITSTATUS(stat_loc));
613 } else if (WIFSIGNALED(stat_loc)) {
614 // Child died, so pretend it returned 1
615 actCall->setRetValue(1);
618 } else if (WIFSTOPPED(stat_loc)) {
619 lyxerr << "LyX: Child (pid: " << pid
620 << ") stopped on signal "
621 << WSTOPSIG(stat_loc)
622 << ". Waiting for child to finish." << endl;
625 lyxerr << "LyX: Something rotten happened while "
626 "waiting for child " << pid << endl;
628 // Child died, so pretend it returned 1
629 actCall->setRetValue(1);
635 forkedCalls.erase(it);
636 actCall->emitSignal();
638 /* start all over: emiting the signal can result
639 * in changing the list (Ab)
641 it = forkedCalls.begin();
649 // Kill the process prematurely and remove it from the list
650 // within tolerance secs
651 void kill(pid_t pid, int tolerance)
653 ListType::iterator it = find_pid(pid);
654 if (it == forkedCalls.end())
657 (*it)->kill(tolerance);
658 forkedCalls.erase(it);
661 } // namespace ForkedCallsController
663 } // namespace support