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