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