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