]> git.lyx.org Git - lyx.git/blob - src/support/forkedcall.C
dont use pragma impementation and interface anymore
[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 void ForkedProcess::kill(int tol)
147 {
148         lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
149         if (pid() == 0) {
150                 lyxerr << "Can't kill non-existent process!" << endl;
151                 return;
152         }
153
154         int const tolerance = std::max(0, tol);
155         if (tolerance == 0) {
156                 // Kill it dead NOW!
157                 Murder::killItDead(0, pid());
158
159         } else {
160                 int ret = lyx::kill(pid(), SIGHUP);
161
162                 // The process is already dead if wait_for_death is false
163                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
164
165                 if (wait_for_death) {
166                         Murder::killItDead(tolerance, pid());
167                 }
168         }
169 }
170
171
172 // Wait for child process to finish. Returns returncode from child.
173 int ForkedProcess::waitForChild()
174 {
175         // We'll pretend that the child returns 1 on all error conditions.
176         retval_ = 1;
177         int status;
178         bool wait = true;
179         while (wait) {
180                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
181                 if (waitrpid == -1) {
182                         lyxerr << "LyX: Error waiting for child:"
183                                << strerror(errno) << endl;
184                         wait = false;
185                 } else if (WIFEXITED(status)) {
186                         // Child exited normally. Update return value.
187                         retval_ = WEXITSTATUS(status);
188                         wait = false;
189                 } else if (WIFSIGNALED(status)) {
190                         lyxerr << "LyX: Child didn't catch signal "
191                                << WTERMSIG(status)
192                                << "and died. Too bad." << endl;
193                         wait = false;
194                 } else if (WIFSTOPPED(status)) {
195                         lyxerr << "LyX: Child (pid: " << pid_
196                                << ") stopped on signal "
197                                << WSTOPSIG(status)
198                                << ". Waiting for child to finish." << endl;
199                 } else {
200                         lyxerr << "LyX: Something rotten happened while "
201                                 "waiting for child " << pid_ << endl;
202                         wait = false;
203                 }
204         }
205         return retval_;
206 }
207
208
209 int Forkedcall::startscript(Starttype wait, string const & what)
210 {
211         if (wait != Wait) {
212                 retval_ = startscript(what, SignalTypePtr());
213                 return retval_;
214         }
215
216         command_ = what;
217         signal_.reset();
218         return runBlocking();
219 }
220
221
222 int Forkedcall::startscript(string const & what, SignalTypePtr signal)
223 {
224         command_ = what;
225         signal_  = signal;
226
227         return runNonBlocking();
228 }
229
230
231 // generate child in background
232 int Forkedcall::generateChild()
233 {
234         // Split command_ up into a char * array
235         int const MAX_ARGV = 255;
236         char *argv[MAX_ARGV];
237
238         string line = command_;
239         int index = 0;
240         for (; index < MAX_ARGV-1; ++index) {
241                 string word;
242                 line = split(line, word, ' ');
243                 if (word.empty())
244                         break;
245
246                 char * tmp = new char[word.length() + 1];
247                 word.copy(tmp, word.length());
248                 tmp[word.length()] = '\0';
249
250                 argv[index] = tmp;
251         }
252         argv[index] = 0;
253
254 #ifndef __EMX__
255         pid_t const cpid = ::fork();
256         if (cpid == 0) {
257                 // Child
258                 execvp(argv[0], argv);
259
260                 // If something goes wrong, we end up here
261                 lyxerr << "execvp of \"" << command_ << "\" failed: "
262                        << strerror(errno) << endl;
263                 _exit(1);
264         }
265 #else
266         pid_t const cpid = spawnvp(P_SESSION|P_DEFAULT|P_MINIMIZE|P_BACKGROUND,
267                                    argv[0], argv);
268 #endif
269
270         if (cpid < 0) {
271                 // Error.
272                 lyxerr << "Could not fork: " << strerror(errno) << endl;
273         }
274
275         // Clean-up.
276         for (int i = 0; i < MAX_ARGV; ++i) {
277                 if (argv[i] == 0)
278                         break;
279                 delete [] argv[i];
280         }
281
282         return cpid;
283 }