]> git.lyx.org Git - lyx.git/blob - src/support/forkedcall.C
Revert the asynchronous child process code to that of LyX 1.3.6.
[lyx.git] / src / support / forkedcall.C
1 /**
2  * \file forkedcall.C
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/forkedcontr.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
42 #ifdef _WIN32
43 # define SIGHUP 1
44 # define SIGKILL 9
45 # include <process.h>
46 # include <windows.h>
47
48 #else
49 # include <cerrno>
50 # include <csignal>
51 # include <cstdlib>
52 # include <unistd.h>
53 # include <sys/types.h>
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         int const tolerance = std::max(0, tol);
184         if (tolerance == 0) {
185                 // Kill it dead NOW!
186                 Murder::killItDead(0, pid());
187
188         } else {
189                 int ret = lyx::support::kill(pid(), SIGHUP);
190
191                 // The process is already dead if wait_for_death is false
192                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
193
194                 if (wait_for_death) {
195                         Murder::killItDead(tolerance, pid());
196                 }
197         }
198 }
199
200
201 // Wait for child process to finish. Returns returncode from child.
202 int ForkedProcess::waitForChild()
203 {
204         // We'll pretend that the child returns 1 on all error conditions.
205         retval_ = 1;
206
207 #if defined (_WIN32)
208         HANDLE const hProcess = HANDLE(pid_);
209
210         DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
211
212         switch (wait_status) {
213         case WAIT_OBJECT_0: {
214                 DWORD exit_code = 0;
215                 if (!GetExitCodeProcess(hProcess, &exit_code)) {
216                         lyxerr << "GetExitCodeProcess failed waiting for child\n"
217                                << getChildErrorMessage() << std::endl;
218                 } else
219                         retval_ = exit_code;
220                 break;
221         }
222         case WAIT_FAILED:
223                 lyxerr << "WaitForSingleObject failed waiting for child\n"
224                        << getChildErrorMessage() << std::endl;
225                 break;
226         }
227
228 #else
229         int status;
230         bool wait = true;
231         while (wait) {
232                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
233                 if (waitrpid == -1) {
234                         lyxerr << "LyX: Error waiting for child:"
235                                << strerror(errno) << endl;
236                         wait = false;
237                 } else if (WIFEXITED(status)) {
238                         // Child exited normally. Update return value.
239                         retval_ = WEXITSTATUS(status);
240                         wait = false;
241                 } else if (WIFSIGNALED(status)) {
242                         lyxerr << "LyX: Child didn't catch signal "
243                                << WTERMSIG(status)
244                                << "and died. Too bad." << endl;
245                         wait = false;
246                 } else if (WIFSTOPPED(status)) {
247                         lyxerr << "LyX: Child (pid: " << pid_
248                                << ") stopped on signal "
249                                << WSTOPSIG(status)
250                                << ". Waiting for child to finish." << endl;
251                 } else {
252                         lyxerr << "LyX: Something rotten happened while "
253                                 "waiting for child " << pid_ << endl;
254                         wait = false;
255                 }
256         }
257 #endif
258         return retval_;
259 }
260
261
262 int Forkedcall::startscript(Starttype wait, string const & what)
263 {
264         if (wait != Wait) {
265                 retval_ = startscript(what, SignalTypePtr());
266                 return retval_;
267         }
268
269         command_ = what;
270         signal_.reset();
271         return run(Wait);
272 }
273
274
275 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
276 {
277         command_ = what;
278         signal_  = signal;
279
280         return run(DontWait);
281 }
282
283
284 // generate child in background
285 int Forkedcall::generateChild()
286 {
287         string line = trim(command_);
288         if (line.empty())
289                 return 1;
290
291         // Split the input command up into an array of words stored
292         // in a contiguous block of memory. The array contains pointers
293         // to each word.
294         // Don't forget the terminating `\0' character.
295         char const * const c_str = line.c_str();
296         vector<char> vec(c_str, c_str + line.size() + 1);
297
298         // Splitting the command up into an array of words means replacing
299         // the whitespace between words with '\0'. Life is complicated
300         // however, because words protected by quotes can contain whitespace.
301         //
302         // The strategy we adopt is:
303         // 1. If we're not inside quotes, then replace white space with '\0'.
304         // 2. If we are inside quotes, then don't replace the white space
305         //    but do remove the quotes themselves. We do this naively by
306         //    replacing the quote with '\0' which is fine if quotes
307         //    delimit the entire word.
308         char inside_quote = 0;
309         vector<char>::iterator it = vec.begin();
310         vector<char>::iterator const end = vec.end();
311         for (; it != end; ++it) {
312                 char const c = *it;
313                 if (!inside_quote) {
314                         if (c == ' ')
315                                 *it = '\0';
316                         else if (c == '\'' || c == '"') {
317 #if defined (_WIN32)
318                                 // How perverse!
319                                 // spawnvp *requires* the quotes or it will
320                                 // split the arg at the internal whitespace!
321                                 // Make shure the quote is a DOS-style one.
322                                 *it = '"';
323 #else
324                                 *it = '\0';
325 #endif
326                                 inside_quote = c;
327                         }
328                 } else if (c == inside_quote) {
329 #if defined (_WIN32)
330                         *it = '"';
331 #else
332                         *it = '\0';
333 #endif
334                         inside_quote = 0;
335                 }
336         }
337
338         // Build an array of pointers to each word.
339         it = vec.begin();
340         vector<char *> argv;
341         char prev = '\0';
342         for (; it != end; ++it) {
343                 if (*it != '\0' && prev == '\0')
344                         argv.push_back(&*it);
345                 prev = *it;
346         }
347         argv.push_back(0);
348
349         // Debug output.
350         if (lyxerr.debugging(Debug::FILES)) {
351                 vector<char *>::iterator ait = argv.begin();
352                 vector<char *>::iterator const aend = argv.end();
353                 lyxerr << "<command>\n\t" << line
354                        << "\n\tInterpretted as:\n\n";
355                 for (; ait != aend; ++ait)
356                         if (*ait)
357                                 lyxerr << '\t'<< *ait << '\n';
358                 lyxerr << "</command>" << std::endl;
359         }
360
361 #if defined (__EMX__)
362         pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
363                                    argv[0], &*argv.begin());
364 #elif defined (_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