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>
55 /////////////////////////////////////////////////////////////////////
59 /////////////////////////////////////////////////////////////////////
64 static void killItDead(int secs, pid_t pid)
67 new Murder(secs, pid);
69 support::kill(pid, SIGKILL);
76 support::kill(pid_, SIGKILL);
77 lyxerr << "Killed " << pid_ << endl;
83 Murder(int secs, pid_t pid)
84 : timeout_(1000*secs, Timeout::ONETIME), pid_(pid)
86 // Connection is closed with this.
87 timeout_.timeout.connect([this](){ kill(); });
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 /////////////////////////////////////////////////////////////////////
273 ForkedCall::ForkedCall(string const & path, string const & lpath)
274 : cmd_prefix_(to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath))))
278 int ForkedCall::startScript(Starttype wait, string const & what)
281 retval_ = startScript(what, sigPtr());
285 command_ = commandPrep(trim(what));
291 int ForkedCall::startScript(string const & what, sigPtr signal)
293 command_ = commandPrep(trim(what));
296 return run(DontWait);
300 // generate child in background
301 int ForkedCall::generateChild()
303 if (command_.empty())
306 // Make sure that a V2 python is run, if available.
307 string const line = cmd_prefix_ +
308 (prefixIs(command_, "python -tt")
309 ? os::python() + command_.substr(10) : command_);
311 #if !defined (_WIN32)
314 // Split the input command up into an array of words stored
315 // in a contiguous block of memory. The array contains pointers
317 // Don't forget the terminating `\0' character.
318 char const * const c_str = line.c_str();
319 vector<char> vec(c_str, c_str + line.size() + 1);
321 // Splitting the command up into an array of words means replacing
322 // the whitespace between words with '\0'. Life is complicated
323 // however, because words protected by quotes can contain whitespace.
325 // The strategy we adopt is:
326 // 1. If we're not inside quotes, then replace white space with '\0'.
327 // 2. If we are inside quotes, then don't replace the white space
328 // but do remove the quotes themselves. We do this naively by
329 // replacing the quote with '\0' which is fine if quotes
330 // delimit the entire word. However, if quotes do not delimit the
331 // entire word (i.e., open quote is inside word), simply discard
332 // them such as not to break the current word.
333 char inside_quote = 0;
334 char c_before_open_quote = ' ';
335 vector<char>::iterator it = vec.begin();
336 vector<char>::iterator itc = vec.begin();
337 vector<char>::iterator const end = vec.end();
338 for (; it != end; ++it, ++itc) {
341 if (c == '\'' || c == '"') {
342 if (c_before_open_quote == ' ')
352 c_before_open_quote = c;
354 } else if (c == inside_quote) {
355 if (c_before_open_quote == ' ')
364 // Clear what remains.
365 for (; itc != end; ++itc)
368 // Build an array of pointers to each word.
372 for (; it != end; ++it) {
373 if (*it != '\0' && prev == '\0')
374 argv.push_back(&*it);
377 argv.push_back(nullptr);
380 if (lyxerr.debugging(Debug::FILES)) {
381 vector<char *>::iterator ait = argv.begin();
382 vector<char *>::iterator const aend = argv.end();
383 lyxerr << "<command>\n\t" << line
384 << "\n\tInterpreted as:\n\n";
385 for (; ait != aend; ++ait)
387 lyxerr << '\t'<< *ait << '\n';
388 lyxerr << "</command>" << endl;
391 pid_t const cpid = ::fork();
394 execvp(argv[0], &*argv.begin());
396 // If something goes wrong, we end up here
397 lyxerr << "execvp of \"" << command_ << "\" failed: "
398 << strerror(errno) << endl;
407 PROCESS_INFORMATION process;
409 memset(&startup, 0, sizeof(STARTUPINFO));
410 memset(&process, 0, sizeof(PROCESS_INFORMATION));
412 startup.cb = sizeof(STARTUPINFO);
414 if (CreateProcess(0, (LPSTR)line.c_str(), 0, 0, FALSE,
415 CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
416 CloseHandle(process.hThread);
417 cpid = (pid_t)process.hProcess;
423 lyxerr << "Could not fork: " << strerror(errno) << endl;
430 /////////////////////////////////////////////////////////////////////
434 /////////////////////////////////////////////////////////////////////
436 namespace ForkedCallQueue {
438 /// A process in the queue
439 typedef pair<string, ForkedCall::sigPtr> Process;
440 /** Add a process to the queue. Processes are forked sequentially
441 * only one is running at a time.
442 * Connect to the returned signal and you'll be informed when
443 * the process has ended.
445 ForkedCall::sigPtr add(string const & process);
447 /// in-progress queue
448 static queue<Process> callQueue_;
450 /// flag whether queue is running
451 static bool running_ = 0;
458 void callback(pid_t, int);
460 ForkedCall::sigPtr add(string const & process)
462 ForkedCall::sigPtr ptr;
463 ptr.reset(new ForkedCall::sig);
464 callQueue_.push(Process(process, ptr));
473 if (callQueue_.empty())
475 Process pro = callQueue_.front();
477 // Bind our chain caller
478 pro.second->connect(callback);
480 //If we fail to fork the process, then emit the signal
481 //to tell the outside world that it failed.
482 if (call.startScript(pro.first, pro.second) > 0)
483 pro.second->operator()(0,1);
487 void callback(pid_t, int)
489 if (callQueue_.empty())
498 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
507 LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
516 } // namespace ForkedCallQueue
519 /////////////////////////////////////////////////////////////////////
521 // ForkedCallsController
523 /////////////////////////////////////////////////////////////////////
526 string const getChildErrorMessage()
528 DWORD const error_code = ::GetLastError();
530 HLOCAL t_message = 0;
531 bool const ok = ::FormatMessage(
532 FORMAT_MESSAGE_ALLOCATE_BUFFER |
533 FORMAT_MESSAGE_FROM_SYSTEM,
535 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
536 (LPTSTR) &t_message, 0, 0
540 ss << "LyX: Error waiting for child: " << error_code;
543 ss << ": " << (LPTSTR)t_message;
544 ::LocalFree(t_message);
546 ss << ": Error unknown.";
553 namespace ForkedCallsController {
555 typedef shared_ptr<ForkedProcess> ForkedProcessPtr;
556 typedef list<ForkedProcessPtr> ListType;
557 typedef ListType::iterator iterator;
560 /// The child processes
561 static ListType forkedCalls;
563 iterator find_pid(pid_t pid)
565 return find_if(forkedCalls.begin(), forkedCalls.end(),
566 lyx::bind(equal_to<pid_t>(),
567 lyx::bind(&ForkedCall::pid, _1),
572 void addCall(ForkedProcess const & newcall)
574 forkedCalls.push_back(newcall.clone());
578 // Check the list of dead children and emit any associated signals.
579 void handleCompletedProcesses()
581 ListType::iterator it = forkedCalls.begin();
582 ListType::iterator end = forkedCalls.end();
584 ForkedProcessPtr actCall = *it;
585 bool remove_it = false;
588 HANDLE const hProcess = HANDLE(actCall->pid());
590 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
592 switch (wait_status) {
596 case WAIT_OBJECT_0: {
598 if (!GetExitCodeProcess(hProcess, &exit_code)) {
599 lyxerr << "GetExitCodeProcess failed waiting for child\n"
600 << getChildErrorMessage() << endl;
601 // Child died, so pretend it returned 1
602 actCall->setRetValue(1);
604 actCall->setRetValue(exit_code);
606 CloseHandle(hProcess);
611 lyxerr << "WaitForSingleObject failed waiting for child\n"
612 << getChildErrorMessage() << endl;
613 actCall->setRetValue(1);
614 CloseHandle(hProcess);
619 pid_t pid = actCall->pid();
621 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
623 if (waitrpid == -1) {
624 lyxerr << "LyX: Error waiting for child: "
625 << strerror(errno) << endl;
627 // Child died, so pretend it returned 1
628 actCall->setRetValue(1);
631 } else if (waitrpid == 0) {
632 // Still running. Move on to the next child.
634 } else if (WIFEXITED(stat_loc)) {
635 // Ok, the return value goes into retval.
636 actCall->setRetValue(WEXITSTATUS(stat_loc));
639 } else if (WIFSIGNALED(stat_loc)) {
640 // Child died, so pretend it returned 1
641 actCall->setRetValue(1);
644 } else if (WIFSTOPPED(stat_loc)) {
645 lyxerr << "LyX: Child (pid: " << pid
646 << ") stopped on signal "
647 << WSTOPSIG(stat_loc)
648 << ". Waiting for child to finish." << endl;
651 lyxerr << "LyX: Something rotten happened while "
652 "waiting for child " << pid << endl;
654 // Child died, so pretend it returned 1
655 actCall->setRetValue(1);
661 forkedCalls.erase(it);
662 actCall->emitSignal();
664 /* start all over: emiting the signal can result
665 * in changing the list (Ab)
667 it = forkedCalls.begin();
675 // Kill the process prematurely and remove it from the list
676 // within tolerance secs
677 void kill(pid_t pid, int tolerance)
679 ListType::iterator it = find_pid(pid);
680 if (it == forkedCalls.end())
683 (*it)->kill(tolerance);
684 forkedCalls.erase(it);
687 } // namespace ForkedCallsController
689 } // namespace support