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"
46 # include <sys/wait.h>
57 /////////////////////////////////////////////////////////////////////
61 /////////////////////////////////////////////////////////////////////
66 static void killItDead(int secs, pid_t pid)
69 new Murder(secs, pid);
71 support::kill(pid, SIGKILL);
78 support::kill(pid_, SIGKILL);
79 lyxerr << "Killed " << pid_ << endl;
85 Murder(int secs, pid_t pid)
86 : timeout_(1000*secs, Timeout::ONETIME), pid_(pid)
88 // Connection is closed with this.
89 timeout_.timeout.connect([this](){ kill(); });
102 /////////////////////////////////////////////////////////////////////
106 /////////////////////////////////////////////////////////////////////
108 ForkedProcess::ForkedProcess()
109 : pid_(0), retval_(0)
113 bool ForkedProcess::IAmAChild = false;
116 void ForkedProcess::emitSignal()
119 signal_->operator()(pid_, retval_);
124 // Spawn the child process
125 int ForkedProcess::run(Starttype type)
128 pid_ = generateChild();
129 if (pid_ <= 0) { // child or fork failed.
132 //we also do this in fork(), too, but maybe someone will try
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 = 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 pid_t ForkedProcess::fork() {
197 #if !defined (HAVE_FORK)
200 pid_t pid = ::fork();
208 // Wait for child process to finish. Returns returncode from child.
209 int ForkedProcess::waitForChild()
211 // We'll pretend that the child returns 1 on all error conditions.
215 HANDLE const hProcess = HANDLE(pid_);
217 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
219 switch (wait_status) {
220 case WAIT_OBJECT_0: {
222 if (!GetExitCodeProcess(hProcess, &exit_code)) {
223 lyxerr << "GetExitCodeProcess failed waiting for child\n"
224 << getChildErrorMessage() << endl;
230 lyxerr << "WaitForSingleObject failed waiting for child\n"
231 << getChildErrorMessage() << endl;
239 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
240 if (waitrpid == -1) {
241 lyxerr << "LyX: Error waiting for child:"
242 << strerror(errno) << endl;
244 } else if (WIFEXITED(status)) {
245 // Child exited normally. Update return value.
246 retval_ = WEXITSTATUS(status);
248 } else if (WIFSIGNALED(status)) {
249 lyxerr << "LyX: Child didn't catch signal "
251 << "and died. Too bad." << endl;
253 } else if (WIFSTOPPED(status)) {
254 lyxerr << "LyX: Child (pid: " << pid_
255 << ") stopped on signal "
257 << ". Waiting for child to finish." << endl;
259 lyxerr << "LyX: Something rotten happened while "
260 "waiting for child " << pid_ << endl;
269 /////////////////////////////////////////////////////////////////////
273 /////////////////////////////////////////////////////////////////////
275 ForkedCall::ForkedCall(string const & path, string const & lpath)
276 : cmd_prefix_(to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath))))
280 int ForkedCall::startScript(Starttype wait, string const & what)
283 retval_ = startScript(what, sigPtr());
287 command_ = commandPrep(trim(what));
293 int ForkedCall::startScript(string const & what, sigPtr signal)
295 command_ = commandPrep(trim(what));
298 return run(DontWait);
302 // generate child in background
303 int ForkedCall::generateChild()
305 if (command_.empty())
308 // Make sure that a V2 python is run, if available.
309 string const line = cmd_prefix_ +
310 (prefixIs(command_, "python -tt")
311 ? os::python() + command_.substr(10) : command_);
313 #if !defined (_WIN32)
316 // Split the input command up into an array of words stored
317 // in a contiguous block of memory. The array contains pointers
319 // Don't forget the terminating `\0' character.
320 char const * const c_str = line.c_str();
321 vector<char> vec(c_str, c_str + line.size() + 1);
323 // Splitting the command up into an array of words means replacing
324 // the whitespace between words with '\0'. Life is complicated
325 // however, because words protected by quotes can contain whitespace.
327 // The strategy we adopt is:
328 // 1. If we're not inside quotes, then replace white space with '\0'.
329 // 2. If we are inside quotes, then don't replace the white space
330 // but do remove the quotes themselves. We do this naively by
331 // replacing the quote with '\0' which is fine if quotes
332 // delimit the entire word. However, if quotes do not delimit the
333 // entire word (i.e., open quote is inside word), simply discard
334 // them such as not to break the current word.
335 char inside_quote = 0;
336 char c_before_open_quote = ' ';
337 vector<char>::iterator it = vec.begin();
338 vector<char>::iterator itc = vec.begin();
339 vector<char>::iterator const end = vec.end();
340 for (; it != end; ++it, ++itc) {
343 if (c == '\'' || c == '"') {
344 if (c_before_open_quote == ' ')
354 c_before_open_quote = c;
356 } else if (c == inside_quote) {
357 if (c_before_open_quote == ' ')
366 // Clear what remains.
367 for (; itc != end; ++itc)
370 // Build an array of pointers to each word.
374 for (; it != end; ++it) {
375 if (*it != '\0' && prev == '\0')
376 argv.push_back(&*it);
379 argv.push_back(nullptr);
382 if (lyxerr.debugging(Debug::FILES)) {
383 vector<char *>::iterator ait = argv.begin();
384 vector<char *>::iterator const aend = argv.end();
385 lyxerr << "<command>\n\t" << line
386 << "\n\tInterpreted as:\n\n";
387 for (; ait != aend; ++ait)
389 lyxerr << '\t'<< *ait << '\n';
390 lyxerr << "</command>" << endl;
393 pid_t const cpid = ::fork();
396 execvp(argv[0], &*argv.begin());
398 // If something goes wrong, we end up here
399 lyxerr << "execvp of \"" << command_ << "\" failed: "
400 << strerror(errno) << endl;
409 PROCESS_INFORMATION process;
411 memset(&startup, 0, sizeof(STARTUPINFO));
412 memset(&process, 0, sizeof(PROCESS_INFORMATION));
414 startup.cb = sizeof(STARTUPINFO);
416 if (CreateProcess(0, (LPSTR)line.c_str(), 0, 0, FALSE,
417 CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
418 CloseHandle(process.hThread);
419 cpid = (pid_t)process.hProcess;
425 lyxerr << "Could not fork: " << strerror(errno) << endl;
432 /////////////////////////////////////////////////////////////////////
436 /////////////////////////////////////////////////////////////////////
438 namespace ForkedCallQueue {
440 /// A process in the queue
441 typedef pair<string, ForkedCall::sigPtr> Process;
442 /** Add a process to the queue. Processes are forked sequentially
443 * only one is running at a time.
444 * Connect to the returned signal and you'll be informed when
445 * the process has ended.
447 ForkedCall::sigPtr add(string const & process);
449 /// in-progress queue
450 static queue<Process> callQueue_;
452 /// flag whether queue is running
453 static bool running_ = false;
460 void callback(pid_t, int);
462 ForkedCall::sigPtr add(string const & process)
464 ForkedCall::sigPtr ptr;
465 ptr.reset(new ForkedCall::sig);
466 callQueue_.push(Process(process, ptr));
475 if (callQueue_.empty())
477 Process pro = callQueue_.front();
479 // Bind our chain caller
480 pro.second->connect(callback);
482 //If we fail to fork the process, then emit the signal
483 //to tell the outside world that it failed.
484 if (call.startScript(pro.first, pro.second) > 0)
485 pro.second->operator()(0,1);
489 void callback(pid_t, int)
491 if (callQueue_.empty())
500 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
509 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
518 } // namespace ForkedCallQueue
521 /////////////////////////////////////////////////////////////////////
523 // ForkedCallsController
525 /////////////////////////////////////////////////////////////////////
528 string const getChildErrorMessage()
530 DWORD const error_code = ::GetLastError();
532 HLOCAL t_message = 0;
533 bool const ok = ::FormatMessage(
534 FORMAT_MESSAGE_ALLOCATE_BUFFER |
535 FORMAT_MESSAGE_FROM_SYSTEM,
537 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
538 (LPTSTR) &t_message, 0, 0
542 ss << "LyX: Error waiting for child: " << error_code;
545 ss << ": " << (LPTSTR)t_message;
546 ::LocalFree(t_message);
548 ss << ": Error unknown.";
555 namespace ForkedCallsController {
557 typedef shared_ptr<ForkedProcess> ForkedProcessPtr;
558 typedef list<ForkedProcessPtr> ListType;
559 typedef ListType::iterator iterator;
562 /// The child processes
563 static ListType forkedCalls;
565 iterator find_pid(pid_t pid)
567 return find_if(forkedCalls.begin(), forkedCalls.end(),
568 lyx::bind(equal_to<pid_t>(),
569 lyx::bind(&ForkedCall::pid, _1),
574 void addCall(ForkedProcess const & newcall)
576 forkedCalls.push_back(newcall.clone());
580 // Check the list of dead children and emit any associated signals.
581 void handleCompletedProcesses()
583 ListType::iterator it = forkedCalls.begin();
584 ListType::iterator end = forkedCalls.end();
586 ForkedProcessPtr actCall = *it;
587 bool remove_it = false;
590 HANDLE const hProcess = HANDLE(actCall->pid());
592 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
594 switch (wait_status) {
598 case WAIT_OBJECT_0: {
600 if (!GetExitCodeProcess(hProcess, &exit_code)) {
601 lyxerr << "GetExitCodeProcess failed waiting for child\n"
602 << getChildErrorMessage() << endl;
603 // Child died, so pretend it returned 1
604 actCall->setRetValue(1);
606 actCall->setRetValue(exit_code);
608 CloseHandle(hProcess);
613 lyxerr << "WaitForSingleObject failed waiting for child\n"
614 << getChildErrorMessage() << endl;
615 actCall->setRetValue(1);
616 CloseHandle(hProcess);
621 pid_t pid = actCall->pid();
623 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
625 if (waitrpid == -1) {
626 lyxerr << "LyX: Error waiting for child: "
627 << strerror(errno) << endl;
629 // Child died, so pretend it returned 1
630 actCall->setRetValue(1);
633 } else if (waitrpid == 0) {
634 // Still running. Move on to the next child.
636 } else if (WIFEXITED(stat_loc)) {
637 // Ok, the return value goes into retval.
638 actCall->setRetValue(WEXITSTATUS(stat_loc));
641 } else if (WIFSIGNALED(stat_loc)) {
642 // Child died, so pretend it returned 1
643 actCall->setRetValue(1);
646 } else if (WIFSTOPPED(stat_loc)) {
647 lyxerr << "LyX: Child (pid: " << pid
648 << ") stopped on signal "
649 << WSTOPSIG(stat_loc)
650 << ". Waiting for child to finish." << endl;
653 lyxerr << "LyX: Something rotten happened while "
654 "waiting for child " << pid << endl;
656 // Child died, so pretend it returned 1
657 actCall->setRetValue(1);
663 forkedCalls.erase(it);
664 actCall->emitSignal();
666 /* start all over: emitting the signal can result
667 * in changing the list (Ab)
669 it = forkedCalls.begin();
677 // Kill the process prematurely and remove it from the list
678 // within tolerance secs
679 void kill(pid_t pid, int tolerance)
681 ListType::iterator it = find_pid(pid);
682 if (it == forkedCalls.end())
685 (*it)->kill(tolerance);
686 forkedCalls.erase(it);
689 } // namespace ForkedCallsController
691 } // namespace support