]> git.lyx.org Git - lyx.git/blob - src/support/forkedcall.C
make "make distcheck" work
[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 <cerrno>
41 #include <csignal>
42 #include <cstdlib>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48
49 #include <vector>
50
51 using std::endl;
52 using std::string;
53 using std::vector;
54
55 #ifndef CXX_GLOBAL_CSTD
56 using std::strerror;
57 #endif
58
59 namespace lyx {
60 namespace support {
61
62
63 namespace {
64
65 class Murder : public boost::signals::trackable {
66 public:
67         //
68         static void killItDead(int secs, pid_t pid)
69         {
70                 if (secs > 0) {
71                         new Murder(secs, pid);
72                 } else if (pid != 0) {
73                         lyx::support::kill(pid, SIGKILL);
74                 }
75         }
76
77         //
78         void kill()
79         {
80                 if (pid_ != 0) {
81                         lyx::support::kill(pid_, SIGKILL);
82                 }
83                 lyxerr << "Killed " << pid_ << std::endl;
84                 delete this;
85         }
86
87 private:
88         //
89         Murder(int secs, pid_t pid)
90                 : timeout_(0), pid_(pid)
91         {
92                 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
93                 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
94                 timeout_->start();
95         }
96
97         //
98         ~Murder()
99         {
100                 delete timeout_;
101         }
102         //
103         Timeout * timeout_;
104         //
105         pid_t pid_;
106 };
107
108 } // namespace anon
109
110
111 ForkedProcess::ForkedProcess()
112         : pid_(0), retval_(0)
113 {}
114
115
116 void ForkedProcess::emitSignal()
117 {
118         if (signal_.get()) {
119                 signal_->operator()(pid_, retval_);
120         }
121 }
122
123
124 // Spawn the child process
125 int ForkedProcess::run(Starttype type)
126 {
127         retval_  = 0;
128         pid_ = generateChild();
129         if (pid_ <= 0) { // child or fork failed.
130                 retval_ = 1;
131                 return retval_;
132         }
133
134         switch (type) {
135         case Wait:
136                 retval_ = waitForChild();
137                 break;
138         case DontWait: {
139                 // Integrate into the Controller
140                 ForkedcallsController & contr = ForkedcallsController::get();
141                 contr.addCall(*this);
142                 break;
143         }
144         }
145
146         return retval_;
147 }
148
149
150 bool ForkedProcess::running() const
151 {
152         if (!pid())
153                 return false;
154
155         // Un-UNIX like, but we don't have much use for
156         // knowing if a zombie exists, so just reap it first.
157         int waitstatus;
158         waitpid(pid(), &waitstatus, WNOHANG);
159
160         // Racy of course, but it will do.
161         if (lyx::support::kill(pid(), 0) && errno == ESRCH)
162                 return false;
163         return true;
164 }
165
166
167 void ForkedProcess::kill(int tol)
168 {
169         lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
170         if (pid() == 0) {
171                 lyxerr << "Can't kill non-existent process!" << endl;
172                 return;
173         }
174
175         int const tolerance = std::max(0, tol);
176         if (tolerance == 0) {
177                 // Kill it dead NOW!
178                 Murder::killItDead(0, pid());
179
180         } else {
181                 int ret = lyx::support::kill(pid(), SIGHUP);
182
183                 // The process is already dead if wait_for_death is false
184                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
185
186                 if (wait_for_death) {
187                         Murder::killItDead(tolerance, pid());
188                 }
189         }
190 }
191
192
193 // Wait for child process to finish. Returns returncode from child.
194 int ForkedProcess::waitForChild()
195 {
196         // We'll pretend that the child returns 1 on all error conditions.
197         retval_ = 1;
198         int status;
199         bool wait = true;
200         while (wait) {
201                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
202                 if (waitrpid == -1) {
203                         lyxerr << "LyX: Error waiting for child:"
204                                << strerror(errno) << endl;
205                         wait = false;
206                 } else if (WIFEXITED(status)) {
207                         // Child exited normally. Update return value.
208                         retval_ = WEXITSTATUS(status);
209                         wait = false;
210                 } else if (WIFSIGNALED(status)) {
211                         lyxerr << "LyX: Child didn't catch signal "
212                                << WTERMSIG(status)
213                                << "and died. Too bad." << endl;
214                         wait = false;
215                 } else if (WIFSTOPPED(status)) {
216                         lyxerr << "LyX: Child (pid: " << pid_
217                                << ") stopped on signal "
218                                << WSTOPSIG(status)
219                                << ". Waiting for child to finish." << endl;
220                 } else {
221                         lyxerr << "LyX: Something rotten happened while "
222                                 "waiting for child " << pid_ << endl;
223                         wait = false;
224                 }
225         }
226         return retval_;
227 }
228
229
230 int Forkedcall::startscript(Starttype wait, string const & what)
231 {
232         if (wait != Wait) {
233                 retval_ = startscript(what, SignalTypePtr());
234                 return retval_;
235         }
236
237         command_ = what;
238         signal_.reset();
239         return run(Wait);
240 }
241
242
243 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
244 {
245         command_ = what;
246         signal_  = signal;
247
248         return run(DontWait);
249 }
250
251
252 // generate child in background
253 int Forkedcall::generateChild()
254 {
255         string line = trim(command_);
256         if (line.empty())
257                 return 1;
258
259         // Split the input command up into an array of words stored
260         // in a contiguous block of memory. The array contains pointers
261         // to each word.
262         // Don't forget the terminating `\0' character.
263         char const * const c_str = line.c_str();
264         vector<char> vec(c_str, c_str + line.size() + 1);
265
266         // Splitting the command up into an array of words means replacing
267         // the whitespace between words with '\0'. Life is complicated
268         // however, because words protected by quotes can contain whitespace.
269         //
270         // The strategy we adopt is:
271         // 1. If we're not inside quotes, then replace white space with '\0'.
272         // 2. If we are inside quotes, then don't replace the white space
273         //    but do remove the quotes themselves. We do this naively by
274         //    replacing the quote with '\0' which is fine if quotes
275         //    delimit the entire word.
276         char inside_quote = 0;
277         vector<char>::iterator it = vec.begin();
278         vector<char>::iterator const end = vec.end();
279         for (; it != end; ++it) {
280                 char const c = *it;
281                 if (!inside_quote) {
282                         if (c == ' ')
283                                 *it = '\0';
284                         else if (c == '\'' || c == '"') {
285                                 *it = '\0';
286                                 inside_quote = c;
287                         }
288                 } else if (c == inside_quote) {
289                         *it = '\0';
290                         inside_quote = 0;
291                 }
292         }
293
294         // Build an array of pointers to each word.
295         it = vec.begin();
296         vector<char *> argv;
297         char prev = '\0';
298         for (; it != end; ++it) {
299                 if (*it != '\0' && prev == '\0')
300                         argv.push_back(&*it);
301                 prev = *it;
302         }
303         argv.push_back(0);
304
305         // Debug output.
306         vector<char *>::iterator ait = argv.begin();
307         vector<char *>::iterator const aend = argv.end();
308         lyxerr << "<command>\n";
309         for (; ait != aend; ++ait)
310                 if (*ait)
311                         lyxerr << '\t'<< *ait << '\n';
312         lyxerr << "</command>" << std::endl;
313
314 #ifndef __EMX__
315         pid_t const cpid = ::fork();
316         if (cpid == 0) {
317                 // Child
318                 execvp(argv[0], &*argv.begin());
319
320                 // If something goes wrong, we end up here
321                 lyxerr << "execvp of \"" << command_ << "\" failed: "
322                        << strerror(errno) << endl;
323                 _exit(1);
324         }
325 #else
326         pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
327                                    argv[0], &*argv.begin());
328 #endif
329
330         if (cpid < 0) {
331                 // Error.
332                 lyxerr << "Could not fork: " << strerror(errno) << endl;
333         }
334
335         return cpid;
336 }
337
338 } // namespace support
339 } // namespace lyx