]> git.lyx.org Git - lyx.git/blob - src/support/forkedcall.C
8e4736fb3f4b32cfa49c33ba04396087f5731c3a
[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 (::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.
261         char const * const c_str = line.c_str();
262         // Don't forget the terminating `\0' character.
263         vector<char> vec(c_str, c_str + line.size() + 1);
264         // Turn the string into an array of words, each terminated with '\0'.
265         std::replace(vec.begin(), vec.end(), ' ', '\0');
266
267         // Build an array of pointers to each word.
268         vector<char>::iterator vit = vec.begin();
269         vector<char>::iterator vend = vec.end();
270         vector<char *> argv;
271         char prev = '\0';
272         for (; vit != vend; ++vit) {
273                 if (*vit != '\0' && prev == '\0')
274                         argv.push_back(&*vit);
275                 prev = *vit;
276         }
277         // Strip quotes. Does so naively, assuming that the word begins
278         // and ends in quotes.
279         vector<char *>::iterator ait = argv.begin();
280         vector<char *>::iterator const aend = argv.end();
281         for (; ait != aend; ++ait) {
282                 char * word = *ait;
283                 std::size_t const len = strlen(word);
284                 if (len >= 2) {
285                         char & first = word[0];
286                         char & last = word[len-1];
287
288                         if (first == last &&
289                             (first == '\'' || first == '"')) {
290                                 first = '\0';
291                                 last = '\0';
292                                 *ait += 1;
293                         }
294                 }
295         }
296
297         ait = argv.begin();
298         for (; ait != aend; ++ait)
299                 std::cout << *ait << std::endl;
300         argv.push_back(0);
301
302 #ifndef __EMX__
303         pid_t const cpid = ::fork();
304         if (cpid == 0) {
305                 // Child
306                 execvp(argv[0], &*argv.begin());
307
308                 // If something goes wrong, we end up here
309                 lyxerr << "execvp of \"" << command_ << "\" failed: "
310                        << strerror(errno) << endl;
311                 _exit(1);
312         }
313 #else
314         pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
315                                    argv[0], &*argv.begin());
316 #endif
317
318         if (cpid < 0) {
319                 // Error.
320                 lyxerr << "Could not fork: " << strerror(errno) << endl;
321         }
322
323         return cpid;
324 }
325
326 } // namespace support
327 } // namespace lyx