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