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