]> git.lyx.org Git - lyx.git/blob - src/support/ForkedCalls.cpp
90ce2993a841290d07e954cafb49b591dd4068ee
[lyx.git] / src / support / ForkedCalls.cpp
1 /**
2  * \file ForkedCalls.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  * \author Angus Leeming
8  * \author Alfredo Braunstein
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "support/ForkedCalls.h"
16
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"
23
24 #include <boost/bind.hpp>
25
26 #include <vector>
27 #include <cerrno>
28 #include <sstream>
29
30 #ifdef _WIN32
31 # define SIGHUP 1
32 # define SIGKILL 9
33 # include <windows.h>
34 # include <process.h>
35 #else
36 # include <csignal>
37 # include <cstdlib>
38 # ifdef HAVE_UNISTD_H
39 #  include <unistd.h>
40 # endif
41 # include <sys/wait.h>
42 # ifndef CXX_GLOBAL_CSTD
43   using std::signal;
44   using std::strerror;
45 # endif
46 #endif
47
48 using boost::bind;
49
50 using std::endl;
51 using std::equal_to;
52 using std::find_if;
53 using std::string;
54 using std::vector;
55
56
57 namespace lyx {
58 namespace support {
59
60 namespace {
61
62 /////////////////////////////////////////////////////////////////////
63 //
64 // Murder
65 //
66 /////////////////////////////////////////////////////////////////////
67
68 class Murder : public boost::signals::trackable {
69 public:
70         //
71         static void killItDead(int secs, pid_t pid)
72         {
73                 if (secs > 0) {
74                         new Murder(secs, pid);
75                 } else if (pid != 0) {
76                         support::kill(pid, SIGKILL);
77                 }
78         }
79
80         //
81         void kill()
82         {
83                 if (pid_ != 0)
84                         support::kill(pid_, SIGKILL);
85                 lyxerr << "Killed " << pid_ << std::endl;
86                 delete this;
87         }
88
89 private:
90         //
91         Murder(int secs, pid_t pid)
92                 : timeout_(0), pid_(pid)
93         {
94                 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
95                 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
96                 timeout_->start();
97         }
98
99         //
100         ~Murder()
101         {
102                 delete timeout_;
103         }
104         //
105         Timeout * timeout_;
106         //
107         pid_t pid_;
108 };
109
110 } // namespace anon
111
112
113 /////////////////////////////////////////////////////////////////////
114 //
115 // ForkedProcess
116 //
117 /////////////////////////////////////////////////////////////////////
118
119 ForkedProcess::ForkedProcess()
120         : pid_(0), retval_(0)
121 {}
122
123
124 void ForkedProcess::emitSignal()
125 {
126         if (signal_.get()) {
127                 signal_->operator()(pid_, retval_);
128         }
129 }
130
131
132 // Spawn the child process
133 int ForkedProcess::run(Starttype type)
134 {
135         retval_  = 0;
136         pid_ = generateChild();
137         if (pid_ <= 0) { // child or fork failed.
138                 retval_ = 1;
139                 return retval_;
140         }
141
142         switch (type) {
143         case Wait:
144                 retval_ = waitForChild();
145                 break;
146         case DontWait: {
147                 // Integrate into the Controller
148                 ForkedCallsController & contr = ForkedCallsController::get();
149                 contr.addCall(*this);
150                 break;
151         }
152         }
153
154         return retval_;
155 }
156
157
158 bool ForkedProcess::running() const
159 {
160         if (!pid())
161                 return false;
162
163 #if !defined (_WIN32)
164         // Un-UNIX like, but we don't have much use for
165         // knowing if a zombie exists, so just reap it first.
166         int waitstatus;
167         waitpid(pid(), &waitstatus, WNOHANG);
168 #endif
169
170         // Racy of course, but it will do.
171         if (support::kill(pid(), 0) && errno == ESRCH)
172                 return false;
173         return true;
174 }
175
176
177 void ForkedProcess::kill(int tol)
178 {
179         lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
180         if (pid() == 0) {
181                 lyxerr << "Can't kill non-existent process!" << endl;
182                 return;
183         }
184
185         // The weird (std::max)(a,b) signature prevents expansion
186         // of an evil MSVC macro.
187         int const tolerance = (std::max)(0, tol);
188         if (tolerance == 0) {
189                 // Kill it dead NOW!
190                 Murder::killItDead(0, pid());
191
192         } else {
193                 int ret = support::kill(pid(), SIGHUP);
194
195                 // The process is already dead if wait_for_death is false
196                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
197
198                 if (wait_for_death) {
199                         Murder::killItDead(tolerance, pid());
200                 }
201         }
202 }
203
204
205 // Wait for child process to finish. Returns returncode from child.
206 int ForkedProcess::waitForChild()
207 {
208         // We'll pretend that the child returns 1 on all error conditions.
209         retval_ = 1;
210
211 #if defined (_WIN32)
212         HANDLE const hProcess = HANDLE(pid_);
213
214         DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
215
216         switch (wait_status) {
217         case WAIT_OBJECT_0: {
218                 DWORD exit_code = 0;
219                 if (!GetExitCodeProcess(hProcess, &exit_code)) {
220                         lyxerr << "GetExitCodeProcess failed waiting for child\n"
221                                << getChildErrorMessage() << std::endl;
222                 } else
223                         retval_ = exit_code;
224                 break;
225         }
226         case WAIT_FAILED:
227                 lyxerr << "WaitForSingleObject failed waiting for child\n"
228                        << getChildErrorMessage() << std::endl;
229                 break;
230         }
231
232 #else
233         int status;
234         bool wait = true;
235         while (wait) {
236                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
237                 if (waitrpid == -1) {
238                         lyxerr << "LyX: Error waiting for child:"
239                                << strerror(errno) << endl;
240                         wait = false;
241                 } else if (WIFEXITED(status)) {
242                         // Child exited normally. Update return value.
243                         retval_ = WEXITSTATUS(status);
244                         wait = false;
245                 } else if (WIFSIGNALED(status)) {
246                         lyxerr << "LyX: Child didn't catch signal "
247                                << WTERMSIG(status)
248                                << "and died. Too bad." << endl;
249                         wait = false;
250                 } else if (WIFSTOPPED(status)) {
251                         lyxerr << "LyX: Child (pid: " << pid_
252                                << ") stopped on signal "
253                                << WSTOPSIG(status)
254                                << ". Waiting for child to finish." << endl;
255                 } else {
256                         lyxerr << "LyX: Something rotten happened while "
257                                 "waiting for child " << pid_ << endl;
258                         wait = false;
259                 }
260         }
261 #endif
262         return retval_;
263 }
264
265
266 /////////////////////////////////////////////////////////////////////
267 //
268 // ForkedCall
269 //
270 /////////////////////////////////////////////////////////////////////
271
272
273 int ForkedCall::startScript(Starttype wait, string const & what)
274 {
275         if (wait != Wait) {
276                 retval_ = startScript(what, SignalTypePtr());
277                 return retval_;
278         }
279
280         command_ = what;
281         signal_.reset();
282         return run(Wait);
283 }
284
285
286 int ForkedCall::startScript(string const & what, SignalTypePtr signal)
287 {
288         command_ = what;
289         signal_  = signal;
290
291         return run(DontWait);
292 }
293
294
295 // generate child in background
296 int ForkedCall::generateChild()
297 {
298         string line = trim(command_);
299         if (line.empty())
300                 return 1;
301
302         // Split the input command up into an array of words stored
303         // in a contiguous block of memory. The array contains pointers
304         // to each word.
305         // Don't forget the terminating `\0' character.
306         char const * const c_str = line.c_str();
307         vector<char> vec(c_str, c_str + line.size() + 1);
308
309         // Splitting the command up into an array of words means replacing
310         // the whitespace between words with '\0'. Life is complicated
311         // however, because words protected by quotes can contain whitespace.
312         //
313         // The strategy we adopt is:
314         // 1. If we're not inside quotes, then replace white space with '\0'.
315         // 2. If we are inside quotes, then don't replace the white space
316         //    but do remove the quotes themselves. We do this naively by
317         //    replacing the quote with '\0' which is fine if quotes
318         //    delimit the entire word.
319         char inside_quote = 0;
320         vector<char>::iterator it = vec.begin();
321         vector<char>::iterator const end = vec.end();
322         for (; it != end; ++it) {
323                 char const c = *it;
324                 if (!inside_quote) {
325                         if (c == ' ')
326                                 *it = '\0';
327                         else if (c == '\'' || c == '"') {
328 #if defined (_WIN32)
329                                 // How perverse!
330                                 // spawnvp *requires* the quotes or it will
331                                 // split the arg at the internal whitespace!
332                                 // Make shure the quote is a DOS-style one.
333                                 *it = '"';
334 #else
335                                 *it = '\0';
336 #endif
337                                 inside_quote = c;
338                         }
339                 } else if (c == inside_quote) {
340 #if defined (_WIN32)
341                         *it = '"';
342 #else
343                         *it = '\0';
344 #endif
345                         inside_quote = 0;
346                 }
347         }
348
349         // Build an array of pointers to each word.
350         it = vec.begin();
351         vector<char *> argv;
352         char prev = '\0';
353         for (; it != end; ++it) {
354                 if (*it != '\0' && prev == '\0')
355                         argv.push_back(&*it);
356                 prev = *it;
357         }
358         argv.push_back(0);
359
360         // Debug output.
361         if (lyxerr.debugging(Debug::FILES)) {
362                 vector<char *>::iterator ait = argv.begin();
363                 vector<char *>::iterator const aend = argv.end();
364                 lyxerr << "<command>\n\t" << line
365                        << "\n\tInterpretted as:\n\n";
366                 for (; ait != aend; ++ait)
367                         if (*ait)
368                                 lyxerr << '\t'<< *ait << '\n';
369                 lyxerr << "</command>" << std::endl;
370         }
371
372 #ifdef _WIN32
373         pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
374 #else // POSIX
375         pid_t const cpid = ::fork();
376         if (cpid == 0) {
377                 // Child
378                 execvp(argv[0], &*argv.begin());
379
380                 // If something goes wrong, we end up here
381                 lyxerr << "execvp of \"" << command_ << "\" failed: "
382                        << strerror(errno) << endl;
383                 _exit(1);
384         }
385 #endif
386
387         if (cpid < 0) {
388                 // Error.
389                 lyxerr << "Could not fork: " << strerror(errno) << endl;
390         }
391
392         return cpid;
393 }
394
395
396 /////////////////////////////////////////////////////////////////////
397 //
398 // ForkedCallQueue
399 //
400 /////////////////////////////////////////////////////////////////////
401
402
403 ForkedCallQueue & ForkedCallQueue::get()
404 {
405         static ForkedCallQueue singleton;
406         return singleton;
407 }
408
409
410 ForkedCall::SignalTypePtr ForkedCallQueue::add(string const & process)
411 {
412         ForkedCall::SignalTypePtr ptr;
413         ptr.reset(new ForkedCall::SignalType);
414         callQueue_.push(Process(process, ptr));
415         if (!running_)
416                 startCaller();
417         return ptr;
418 }
419
420
421 void ForkedCallQueue::callNext()
422 {
423         if (callQueue_.empty())
424                 return;
425         Process pro = callQueue_.front();
426         callQueue_.pop();
427         // Bind our chain caller
428         pro.second->connect(boost::bind(&ForkedCallQueue::callback,
429                                          this, _1, _2));
430         ForkedCall call;
431         // If we fail to fork the process, then emit the signal
432         // to tell the outside world that it failed.
433         if (call.startScript(pro.first, pro.second) > 0)
434                 pro.second->operator()(0,1);
435 }
436
437
438 void ForkedCallQueue::callback(pid_t, int)
439 {
440         if (callQueue_.empty())
441                 stopCaller();
442         else
443                 callNext();
444 }
445
446
447 ForkedCallQueue::ForkedCallQueue()
448         : running_(false)
449 {}
450
451
452 void ForkedCallQueue::startCaller()
453 {
454         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
455         running_ = true ;
456         callNext();
457 }
458
459
460 void ForkedCallQueue::stopCaller()
461 {
462         running_ = false ;
463         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
464 }
465
466
467 bool ForkedCallQueue::running() const
468 {
469         return running_ ;
470 }
471
472
473 /////////////////////////////////////////////////////////////////////
474 //
475 // ForkedCallsController
476 //
477 /////////////////////////////////////////////////////////////////////
478
479 #if defined(_WIN32)
480 string const getChildErrorMessage()
481 {
482         DWORD const error_code = ::GetLastError();
483
484         HLOCAL t_message = 0;
485         bool const ok = ::FormatMessage(
486                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
487                 FORMAT_MESSAGE_FROM_SYSTEM,
488                 0, error_code,
489                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
490                 (LPTSTR) &t_message, 0, 0
491                 ) != 0;
492
493         std::ostringstream ss;
494         ss << "LyX: Error waiting for child: " << error_code;
495
496         if (ok) {
497                 ss << ": " << (LPTSTR)t_message;
498                 ::LocalFree(t_message);
499         } else
500                 ss << ": Error unknown.";
501
502         return ss.str();
503 }
504 #endif
505
506
507 // Ensure, that only one controller exists inside process
508 ForkedCallsController & ForkedCallsController::get()
509 {
510         static ForkedCallsController singleton;
511         return singleton;
512 }
513
514
515 ForkedCallsController::ForkedCallsController()
516 {}
517
518
519 // open question: should we stop childs here?
520 // Asger says no: I like to have my xdvi open after closing LyX. Maybe
521 // I want to print or something.
522 ForkedCallsController::~ForkedCallsController()
523 {}
524
525
526 void ForkedCallsController::addCall(ForkedProcess const & newcall)
527 {
528         forkedCalls.push_back(newcall.clone());
529 }
530
531
532 // Check the list of dead children and emit any associated signals.
533 void ForkedCallsController::handleCompletedProcesses()
534 {
535         ListType::iterator it  = forkedCalls.begin();
536         ListType::iterator end = forkedCalls.end();
537         while (it != end) {
538                 ForkedProcessPtr actCall = *it;
539                 bool remove_it = false;
540
541 #if defined(_WIN32)
542                 HANDLE const hProcess = HANDLE(actCall->pid());
543
544                 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
545
546                 switch (wait_status) {
547                 case WAIT_TIMEOUT:
548                         // Still running
549                         break;
550                 case WAIT_OBJECT_0: {
551                         DWORD exit_code = 0;
552                         if (!GetExitCodeProcess(hProcess, &exit_code)) {
553                                 lyxerr << "GetExitCodeProcess failed waiting for child\n"
554                                        << getChildErrorMessage() << std::endl;
555                                 // Child died, so pretend it returned 1
556                                 actCall->setRetValue(1);
557                         } else {
558                                 actCall->setRetValue(exit_code);
559                         }
560                         remove_it = true;
561                         break;
562                 }
563                 case WAIT_FAILED:
564                         lyxerr << "WaitForSingleObject failed waiting for child\n"
565                                << getChildErrorMessage() << std::endl;
566                         actCall->setRetValue(1);
567                         remove_it = true;
568                         break;
569                 }
570 #else
571                 pid_t pid = actCall->pid();
572                 int stat_loc;
573                 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
574
575                 if (waitrpid == -1) {
576                         lyxerr << "LyX: Error waiting for child: "
577                                << strerror(errno) << endl;
578
579                         // Child died, so pretend it returned 1
580                         actCall->setRetValue(1);
581                         remove_it = true;
582
583                 } else if (waitrpid == 0) {
584                         // Still running. Move on to the next child.
585
586                 } else if (WIFEXITED(stat_loc)) {
587                         // Ok, the return value goes into retval.
588                         actCall->setRetValue(WEXITSTATUS(stat_loc));
589                         remove_it = true;
590
591                 } else if (WIFSIGNALED(stat_loc)) {
592                         // Child died, so pretend it returned 1
593                         actCall->setRetValue(1);
594                         remove_it = true;
595
596                 } else if (WIFSTOPPED(stat_loc)) {
597                         lyxerr << "LyX: Child (pid: " << pid
598                                << ") stopped on signal "
599                                << WSTOPSIG(stat_loc)
600                                << ". Waiting for child to finish." << endl;
601
602                 } else {
603                         lyxerr << "LyX: Something rotten happened while "
604                                 "waiting for child " << pid << endl;
605
606                         // Child died, so pretend it returned 1
607                         actCall->setRetValue(1);
608                         remove_it = true;
609                 }
610 #endif
611
612                 if (remove_it) {
613                         forkedCalls.erase(it);
614                         actCall->emitSignal();
615
616                         /* start all over: emiting the signal can result
617                          * in changing the list (Ab)
618                          */
619                         it = forkedCalls.begin();
620                 } else {
621                         ++it;
622                 }
623         }
624 }
625
626
627 ForkedCallsController::iterator ForkedCallsController::find_pid(pid_t pid)
628 {
629         return find_if(forkedCalls.begin(), forkedCalls.end(),
630                        bind(equal_to<pid_t>(),
631                             bind(&ForkedCall::pid, _1),
632                             pid));
633 }
634
635
636 // Kill the process prematurely and remove it from the list
637 // within tolerance secs
638 void ForkedCallsController::kill(pid_t pid, int tolerance)
639 {
640         ListType::iterator it = find_pid(pid);
641         if (it == forkedCalls.end())
642                 return;
643
644         (*it)->kill(tolerance);
645         forkedCalls.erase(it);
646 }
647
648 } // namespace support
649 } // namespace lyx