]> git.lyx.org Git - lyx.git/blob - src/support/forkedcall.C
split LyXText::rowlist_ into individual Paragraph::rows_ chunks
[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 using std::endl;
46
47 #ifndef CXX_GLOBAL_CSTD
48 using std::strerror;
49 #endif
50
51 namespace lyx {
52 namespace support {
53
54
55 namespace {
56
57 class Murder : public boost::signals::trackable {
58 public:
59         //
60         static void killItDead(int secs, pid_t pid)
61         {
62                 if (secs > 0) {
63                         new Murder(secs, pid);
64                 } else if (pid != 0) {
65                         lyx::support::kill(pid, SIGKILL);
66                 }
67         }
68
69         //
70         void kill()
71         {
72                 if (pid_ != 0) {
73                         lyx::support::kill(pid_, SIGKILL);
74                 }
75                 lyxerr << "Killed " << pid_ << std::endl;
76                 delete this;
77         }
78
79 private:
80         //
81         Murder(int secs, pid_t pid)
82                 : timeout_(0), pid_(pid)
83         {
84                 timeout_ = new Timeout(1000*secs, Timeout::ONETIME);
85                 timeout_->timeout.connect(boost::bind(&Murder::kill, this));
86                 timeout_->start();
87         }
88
89         //
90         ~Murder()
91         {
92                 delete timeout_;
93         }
94         //
95         Timeout * timeout_;
96         //
97         pid_t pid_;
98 };
99
100 } // namespace anon
101
102
103 ForkedProcess::ForkedProcess()
104         : pid_(0), retval_(0)
105 {}
106
107
108 void ForkedProcess::emitSignal()
109 {
110         if (signal_.get()) {
111                 signal_->operator()(pid_, retval_);
112         }
113 }
114
115
116 // Wait for child process to finish.
117 int ForkedProcess::runBlocking()
118 {
119         retval_  = 0;
120         pid_ = generateChild();
121         if (pid_ <= 0) { // child or fork failed.
122                 retval_ = 1;
123                 return retval_;
124         }
125
126         retval_ = waitForChild();
127         return retval_;
128 }
129
130
131 // Do not wait for child process to finish.
132 int ForkedProcess::runNonBlocking()
133 {
134         retval_ = 0;
135         pid_ = generateChild();
136         if (pid_ <= 0) { // child or fork failed.
137                 retval_ = 1;
138                 return retval_;
139         }
140
141         // Non-blocking execution.
142         // Integrate into the Controller
143         ForkedcallsController & contr = ForkedcallsController::get();
144         contr.addCall(*this);
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 runBlocking();
240 }
241
242
243 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
244 {
245         command_ = what;
246         signal_  = signal;
247
248         return runNonBlocking();
249 }
250
251
252 // generate child in background
253 int Forkedcall::generateChild()
254 {
255         // Split command_ up into a char * array
256         int const MAX_ARGV = 255;
257         char *argv[MAX_ARGV];
258
259         string line = command_;
260         int index = 0;
261         for (; index < MAX_ARGV-1; ++index) {
262                 string word;
263                 line = split(line, word, ' ');
264                 if (word.empty())
265                         break;
266
267                 char * tmp = new char[word.length() + 1];
268                 word.copy(tmp, word.length());
269                 tmp[word.length()] = '\0';
270
271                 argv[index] = tmp;
272         }
273         argv[index] = 0;
274
275 #ifndef __EMX__
276         pid_t const cpid = ::fork();
277         if (cpid == 0) {
278                 // Child
279                 execvp(argv[0], argv);
280
281                 // If something goes wrong, we end up here
282                 lyxerr << "execvp of \"" << command_ << "\" failed: "
283                        << strerror(errno) << endl;
284                 _exit(1);
285         }
286 #else
287         pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
288                                    argv[0], argv);
289 #endif
290
291         if (cpid < 0) {
292                 // Error.
293                 lyxerr << "Could not fork: " << strerror(errno) << endl;
294         }
295
296         // Clean-up.
297         for (int i = 0; i < MAX_ARGV; ++i) {
298                 if (argv[i] == 0)
299                         break;
300                 delete [] argv[i];
301         }
302
303         return cpid;
304 }
305
306 } // namespace support
307 } // namespace lyx