]> git.lyx.org Git - lyx.git/blob - src/support/Forkedcall.cpp
fix warning on possibly(?) unused precompiled headers due to different -fPic settings...
[lyx.git] / src / support / Forkedcall.cpp
1 /**
2  * \file Forkedcall.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  *
8  * Interface cleaned up by
9  * \author Angus Leeming
10  *
11  * Full author contact details are available in file CREDITS.
12  *
13  * An instance of Class Forkedcall represents a single child process.
14  *
15  * Class Forkedcall uses fork() and execvp() to lauch the child process.
16  *
17  * Once launched, control is returned immediately to the parent process
18  * but a Signal can be emitted upon completion of the child.
19  *
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
22  * function.
23  */
24
25 #include <config.h>
26
27 #include "support/Forkedcall.h"
28 #include "support/ForkedcallsController.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
31 #include "support/filetools.h"
32 #include "support/os.h"
33 #include "support/Timeout.h"
34
35 #include "debug.h"
36
37 #include <boost/bind.hpp>
38
39 #include <vector>
40 #include <cerrno>
41
42 #ifdef _WIN32
43 # define SIGHUP 1
44 # define SIGKILL 9
45 # include <process.h>
46 # include <windows.h>
47
48 #else
49 # include <csignal>
50 # include <cstdlib>
51 # ifdef HAVE_UNISTD_H
52 #  include <unistd.h>
53 # endif
54 # include <sys/wait.h>
55 #endif
56
57 using std::endl;
58 using std::string;
59 using std::vector;
60
61 #ifndef CXX_GLOBAL_CSTD
62 using std::strerror;
63 #endif
64
65 namespace lyx {
66 namespace support {
67
68
69 namespace {
70
71 class Murder : public boost::signals::trackable {
72 public:
73         //
74         static void killItDead(int secs, pid_t pid)
75         {
76                 if (secs > 0) {
77                         new Murder(secs, pid);
78                 } else if (pid != 0) {
79                         lyx::support::kill(pid, SIGKILL);
80                 }
81         }
82
83         //
84         void kill()
85         {
86                 if (pid_ != 0) {
87                         lyx::support::kill(pid_, SIGKILL);
88                 }
89                 lyxerr << "Killed " << pid_ << std::endl;
90                 delete this;
91         }
92
93 private:
94         //
95         Murder(int secs, pid_t pid)
96                 : timeout_(0), pid_(pid)
97         {
98                 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
99                 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
100                 timeout_->start();
101         }
102
103         //
104         ~Murder()
105         {
106                 delete timeout_;
107         }
108         //
109         Timeout * timeout_;
110         //
111         pid_t pid_;
112 };
113
114 } // namespace anon
115
116
117 ForkedProcess::ForkedProcess()
118         : pid_(0), retval_(0)
119 {}
120
121
122 void ForkedProcess::emitSignal()
123 {
124         if (signal_.get()) {
125                 signal_->operator()(pid_, retval_);
126         }
127 }
128
129
130 // Spawn the child process
131 int ForkedProcess::run(Starttype type)
132 {
133         retval_  = 0;
134         pid_ = generateChild();
135         if (pid_ <= 0) { // child or fork failed.
136                 retval_ = 1;
137                 return retval_;
138         }
139
140         switch (type) {
141         case Wait:
142                 retval_ = waitForChild();
143                 break;
144         case DontWait: {
145                 // Integrate into the Controller
146                 ForkedcallsController & contr = ForkedcallsController::get();
147                 contr.addCall(*this);
148                 break;
149         }
150         }
151
152         return retval_;
153 }
154
155
156 bool ForkedProcess::running() const
157 {
158         if (!pid())
159                 return false;
160
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.
164         int waitstatus;
165         waitpid(pid(), &waitstatus, WNOHANG);
166 #endif
167
168         // Racy of course, but it will do.
169         if (lyx::support::kill(pid(), 0) && errno == ESRCH)
170                 return false;
171         return true;
172 }
173
174
175 void ForkedProcess::kill(int tol)
176 {
177         lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
178         if (pid() == 0) {
179                 lyxerr << "Can't kill non-existent process!" << endl;
180                 return;
181         }
182
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) {
187                 // Kill it dead NOW!
188                 Murder::killItDead(0, pid());
189
190         } else {
191                 int ret = lyx::support::kill(pid(), SIGHUP);
192
193                 // The process is already dead if wait_for_death is false
194                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
195
196                 if (wait_for_death) {
197                         Murder::killItDead(tolerance, pid());
198                 }
199         }
200 }
201
202
203 // Wait for child process to finish. Returns returncode from child.
204 int ForkedProcess::waitForChild()
205 {
206         // We'll pretend that the child returns 1 on all error conditions.
207         retval_ = 1;
208
209 #if defined (_WIN32)
210         HANDLE const hProcess = HANDLE(pid_);
211
212         DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
213
214         switch (wait_status) {
215         case WAIT_OBJECT_0: {
216                 DWORD exit_code = 0;
217                 if (!GetExitCodeProcess(hProcess, &exit_code)) {
218                         lyxerr << "GetExitCodeProcess failed waiting for child\n"
219                                << getChildErrorMessage() << std::endl;
220                 } else
221                         retval_ = exit_code;
222                 break;
223         }
224         case WAIT_FAILED:
225                 lyxerr << "WaitForSingleObject failed waiting for child\n"
226                        << getChildErrorMessage() << std::endl;
227                 break;
228         }
229
230 #else
231         int status;
232         bool wait = true;
233         while (wait) {
234                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
235                 if (waitrpid == -1) {
236                         lyxerr << "LyX: Error waiting for child:"
237                                << strerror(errno) << endl;
238                         wait = false;
239                 } else if (WIFEXITED(status)) {
240                         // Child exited normally. Update return value.
241                         retval_ = WEXITSTATUS(status);
242                         wait = false;
243                 } else if (WIFSIGNALED(status)) {
244                         lyxerr << "LyX: Child didn't catch signal "
245                                << WTERMSIG(status)
246                                << "and died. Too bad." << endl;
247                         wait = false;
248                 } else if (WIFSTOPPED(status)) {
249                         lyxerr << "LyX: Child (pid: " << pid_
250                                << ") stopped on signal "
251                                << WSTOPSIG(status)
252                                << ". Waiting for child to finish." << endl;
253                 } else {
254                         lyxerr << "LyX: Something rotten happened while "
255                                 "waiting for child " << pid_ << endl;
256                         wait = false;
257                 }
258         }
259 #endif
260         return retval_;
261 }
262
263
264 int Forkedcall::startscript(Starttype wait, string const & what)
265 {
266         if (wait != Wait) {
267                 retval_ = startscript(what, SignalTypePtr());
268                 return retval_;
269         }
270
271         command_ = what;
272         signal_.reset();
273         return run(Wait);
274 }
275
276
277 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
278 {
279         command_ = what;
280         signal_  = signal;
281
282         return run(DontWait);
283 }
284
285
286 // generate child in background
287 int Forkedcall::generateChild()
288 {
289         string line = trim(command_);
290         if (line.empty())
291                 return 1;
292
293         // Split the input command up into an array of words stored
294         // in a contiguous block of memory. The array contains pointers
295         // to each word.
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);
299
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.
303         //
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) {
314                 char const c = *it;
315                 if (!inside_quote) {
316                         if (c == ' ')
317                                 *it = '\0';
318                         else if (c == '\'' || c == '"') {
319 #if defined (_WIN32)
320                                 // How perverse!
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.
324                                 *it = '"';
325 #else
326                                 *it = '\0';
327 #endif
328                                 inside_quote = c;
329                         }
330                 } else if (c == inside_quote) {
331 #if defined (_WIN32)
332                         *it = '"';
333 #else
334                         *it = '\0';
335 #endif
336                         inside_quote = 0;
337                 }
338         }
339
340         // Build an array of pointers to each word.
341         it = vec.begin();
342         vector<char *> argv;
343         char prev = '\0';
344         for (; it != end; ++it) {
345                 if (*it != '\0' && prev == '\0')
346                         argv.push_back(&*it);
347                 prev = *it;
348         }
349         argv.push_back(0);
350
351         // Debug output.
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)
358                         if (*ait)
359                                 lyxerr << '\t'<< *ait << '\n';
360                 lyxerr << "</command>" << std::endl;
361         }
362
363 #ifdef _WIN32
364         pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
365 #else // POSIX
366         pid_t const cpid = ::fork();
367         if (cpid == 0) {
368                 // Child
369                 execvp(argv[0], &*argv.begin());
370
371                 // If something goes wrong, we end up here
372                 lyxerr << "execvp of \"" << command_ << "\" failed: "
373                        << strerror(errno) << endl;
374                 _exit(1);
375         }
376 #endif
377
378         if (cpid < 0) {
379                 // Error.
380                 lyxerr << "Could not fork: " << strerror(errno) << endl;
381         }
382
383         return cpid;
384 }
385
386 } // namespace support
387 } // namespace lyx