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