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>
53 # include <sys/types.h>
54 # include <sys/wait.h>
61 #ifndef CXX_GLOBAL_CSTD
71 class Murder : public boost::signals::trackable {
74 static void killItDead(int secs, pid_t pid)
77 new Murder(secs, pid);
78 } else if (pid != 0) {
79 lyx::support::kill(pid, SIGKILL);
87 lyx::support::kill(pid_, SIGKILL);
89 lyxerr << "Killed " << pid_ << std::endl;
95 Murder(int secs, pid_t pid)
96 : timeout_(0), pid_(pid)
98 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
99 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
117 ForkedProcess::ForkedProcess()
118 : pid_(0), retval_(0)
122 void ForkedProcess::emitSignal()
125 signal_->operator()(pid_, retval_);
130 // Spawn the child process
131 int ForkedProcess::run(Starttype type)
134 pid_ = generateChild();
135 if (pid_ <= 0) { // child or fork failed.
142 retval_ = waitForChild();
145 // Integrate into the Controller
146 ForkedcallsController & contr = ForkedcallsController::get();
147 contr.addCall(*this);
156 bool ForkedProcess::running() const
161 #if !defined (_WIN32)
162 // Un-UNIX like, but we don't have much use for
163 // knowing if a zombie exists, so just reap it first.
165 waitpid(pid(), &waitstatus, WNOHANG);
168 // Racy of course, but it will do.
169 if (lyx::support::kill(pid(), 0) && errno == ESRCH)
175 void ForkedProcess::kill(int tol)
177 lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
179 lyxerr << "Can't kill non-existent process!" << endl;
183 // The weird (std::max)(a,b) signature prevents expansion
184 // of an evil MSVC macro.
185 int const tolerance = (std::max)(0, tol);
186 if (tolerance == 0) {
188 Murder::killItDead(0, pid());
191 int ret = lyx::support::kill(pid(), SIGHUP);
193 // The process is already dead if wait_for_death is false
194 bool const wait_for_death = (ret == 0 && errno != ESRCH);
196 if (wait_for_death) {
197 Murder::killItDead(tolerance, pid());
203 // Wait for child process to finish. Returns returncode from child.
204 int ForkedProcess::waitForChild()
206 // We'll pretend that the child returns 1 on all error conditions.
210 HANDLE const hProcess = HANDLE(pid_);
212 DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
214 switch (wait_status) {
215 case WAIT_OBJECT_0: {
217 if (!GetExitCodeProcess(hProcess, &exit_code)) {
218 lyxerr << "GetExitCodeProcess failed waiting for child\n"
219 << getChildErrorMessage() << std::endl;
225 lyxerr << "WaitForSingleObject failed waiting for child\n"
226 << getChildErrorMessage() << std::endl;
234 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
235 if (waitrpid == -1) {
236 lyxerr << "LyX: Error waiting for child:"
237 << strerror(errno) << endl;
239 } else if (WIFEXITED(status)) {
240 // Child exited normally. Update return value.
241 retval_ = WEXITSTATUS(status);
243 } else if (WIFSIGNALED(status)) {
244 lyxerr << "LyX: Child didn't catch signal "
246 << "and died. Too bad." << endl;
248 } else if (WIFSTOPPED(status)) {
249 lyxerr << "LyX: Child (pid: " << pid_
250 << ") stopped on signal "
252 << ". Waiting for child to finish." << endl;
254 lyxerr << "LyX: Something rotten happened while "
255 "waiting for child " << pid_ << endl;
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;
363 #if defined (__EMX__)
364 pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
365 argv[0], &*argv.begin());
366 #elif defined (_WIN32)
367 pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
369 pid_t const cpid = ::fork();
372 execvp(argv[0], &*argv.begin());
374 // If something goes wrong, we end up here
375 lyxerr << "execvp of \"" << command_ << "\" failed: "
376 << strerror(errno) << endl;
383 lyxerr << "Could not fork: " << strerror(errno) << endl;
389 } // namespace support