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>
55 # include <sys/wait.h>
62 #ifndef CXX_GLOBAL_CSTD
72 class Murder : public boost::signals::trackable {
75 static void killItDead(int secs, pid_t pid)
78 new Murder(secs, pid);
79 } else if (pid != 0) {
80 lyx::support::kill(pid, SIGKILL);
88 lyx::support::kill(pid_, SIGKILL);
90 lyxerr << "Killed " << pid_ << std::endl;
96 Murder(int secs, pid_t pid)
97 : timeout_(0), pid_(pid)
99 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
100 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
118 ForkedProcess::ForkedProcess()
119 : pid_(0), retval_(0)
123 void ForkedProcess::emitSignal()
126 signal_->operator()(pid_, retval_);
131 // Spawn the child process
132 int ForkedProcess::run(Starttype type)
135 pid_ = generateChild();
136 if (pid_ <= 0) { // child or fork failed.
143 retval_ = waitForChild();
146 // Integrate into the Controller
147 ForkedcallsController & contr = ForkedcallsController::get();
148 contr.addCall(*this);
157 bool ForkedProcess::running() const
162 #if !defined (_WIN32)
163 // Un-UNIX like, but we don't have much use for
164 // knowing if a zombie exists, so just reap it first.
166 waitpid(pid(), &waitstatus, WNOHANG);
169 // Racy of course, but it will do.
170 if (lyx::support::kill(pid(), 0) && errno == ESRCH)
176 void ForkedProcess::kill(int tol)
178 lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
180 lyxerr << "Can't kill non-existent process!" << endl;
184 // The weird (std::max)(a,b) signature prevents expansion
185 // of an evil MSVC macro.
186 int const tolerance = (std::max)(0, tol);
187 if (tolerance == 0) {
189 Murder::killItDead(0, pid());
192 int ret = lyx::support::kill(pid(), SIGHUP);
194 // The process is already dead if wait_for_death is false
195 bool const wait_for_death = (ret == 0 && errno != ESRCH);
197 if (wait_for_death) {
198 Murder::killItDead(tolerance, pid());
204 // Wait for child process to finish. Returns returncode from child.
205 int ForkedProcess::waitForChild()
207 // We'll pretend that the child returns 1 on all error conditions.
211 HANDLE const hProcess = HANDLE(pid_);
213 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
215 switch (wait_status) {
216 case WAIT_OBJECT_0: {
218 if (!GetExitCodeProcess(hProcess, &exit_code)) {
219 lyxerr << "GetExitCodeProcess failed waiting for child\n"
220 << getChildErrorMessage() << std::endl;
226 lyxerr << "WaitForSingleObject failed waiting for child\n"
227 << getChildErrorMessage() << std::endl;
235 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
236 if (waitrpid == -1) {
237 lyxerr << "LyX: Error waiting for child:"
238 << strerror(errno) << endl;
240 } else if (WIFEXITED(status)) {
241 // Child exited normally. Update return value.
242 retval_ = WEXITSTATUS(status);
244 } else if (WIFSIGNALED(status)) {
245 lyxerr << "LyX: Child didn't catch signal "
247 << "and died. Too bad." << endl;
249 } else if (WIFSTOPPED(status)) {
250 lyxerr << "LyX: Child (pid: " << pid_
251 << ") stopped on signal "
253 << ". Waiting for child to finish." << endl;
255 lyxerr << "LyX: Something rotten happened while "
256 "waiting for child " << pid_ << endl;
265 int Forkedcall::startscript(Starttype wait, string const & what)
268 retval_ = startscript(what, SignalTypePtr());
278 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
283 return run(DontWait);
287 // generate child in background
288 int Forkedcall::generateChild()
290 string line = trim(command_);
294 // Split the input command up into an array of words stored
295 // in a contiguous block of memory. The array contains pointers
297 // Don't forget the terminating `\0' character.
298 char const * const c_str = line.c_str();
299 vector<char> vec(c_str, c_str + line.size() + 1);
301 // Splitting the command up into an array of words means replacing
302 // the whitespace between words with '\0'. Life is complicated
303 // however, because words protected by quotes can contain whitespace.
305 // The strategy we adopt is:
306 // 1. If we're not inside quotes, then replace white space with '\0'.
307 // 2. If we are inside quotes, then don't replace the white space
308 // but do remove the quotes themselves. We do this naively by
309 // replacing the quote with '\0' which is fine if quotes
310 // delimit the entire word.
311 char inside_quote = 0;
312 vector<char>::iterator it = vec.begin();
313 vector<char>::iterator const end = vec.end();
314 for (; it != end; ++it) {
319 else if (c == '\'' || c == '"') {
322 // spawnvp *requires* the quotes or it will
323 // split the arg at the internal whitespace!
324 // Make shure the quote is a DOS-style one.
331 } 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>" << std::endl;
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