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