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