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