summaryrefslogtreecommitdiffabout
authorzautrix <zautrix>2004-07-03 17:03:05 (UTC)
committer zautrix <zautrix>2004-07-03 17:03:05 (UTC)
commitd6c945f1c48c6b6742751177d07e88dca3f3044d (patch) (unidiff)
tree8720a31b685480503aa3b5a3b3328dcddcdbc6cb
parent65ed57d77ba421169b62f46f59ae6b1d7a228e3d (diff)
downloadkdepimpi-d6c945f1c48c6b6742751177d07e88dca3f3044d.zip
kdepimpi-d6c945f1c48c6b6742751177d07e88dca3f3044d.tar.gz
kdepimpi-d6c945f1c48c6b6742751177d07e88dca3f3044d.tar.bz2
Added 4 opie files. Updated pro file.
Diffstat (more/less context) (show whitespace changes)
-rw-r--r--microkde/kapplication.cpp5
-rw-r--r--microkde/kapplication.h2
-rw-r--r--microkde/microkdeE.pro5
-rw-r--r--microkde/oprocctrl.cpp285
-rw-r--r--microkde/oprocctrl.h129
-rw-r--r--microkde/oprocess.cpp951
-rw-r--r--microkde/oprocess.h761
7 files changed, 2138 insertions, 0 deletions
diff --git a/microkde/kapplication.cpp b/microkde/kapplication.cpp
index a1d00a8..77ceac5 100644
--- a/microkde/kapplication.cpp
+++ b/microkde/kapplication.cpp
@@ -24,3 +24,8 @@ QString KApplication::randomString(int length)
24 } 24 }
25 return str; 25 return str;
26} 26}
27 int KApplication::execDialog( QDialog* d )
28{
29 d->showMaximized();
30 return d->exec();
31}
diff --git a/microkde/kapplication.h b/microkde/kapplication.h
index 47e64e7..77206f5 100644
--- a/microkde/kapplication.h
+++ b/microkde/kapplication.h
@@ -2,6 +2,7 @@
2#define MINIKDE_KAPPLICATION_H 2#define MINIKDE_KAPPLICATION_H
3 3
4#include "qstring.h" 4#include "qstring.h"
5#include <qdialog.h>
5 6
6class KApplication 7class KApplication
7{ 8{
@@ -15,6 +16,7 @@ class KApplication
15 * @return the random string 16 * @return the random string
16 */ 17 */
17 static QString randomString(int length); 18 static QString randomString(int length);
19 static int execDialog( QDialog* );
18}; 20};
19 21
20 22
diff --git a/microkde/microkdeE.pro b/microkde/microkdeE.pro
index 8d04123..4ee4dd7 100644
--- a/microkde/microkdeE.pro
+++ b/microkde/microkdeE.pro
@@ -55,6 +55,9 @@ KDGanttMinimizeSplitter.h \
55 kurl.h \ 55 kurl.h \
56 ofileselector_p.h \ 56 ofileselector_p.h \
57 ofontselector.h \ 57 ofontselector.h \
58oprocctrl.h \
59oprocess.h \
60osmartpointer.h \
58 kdeui/kguiitem.h \ 61 kdeui/kguiitem.h \
59 kdeui/kaction.h \ 62 kdeui/kaction.h \
60 kdeui/kactionclasses.h \ 63 kdeui/kactionclasses.h \
@@ -127,6 +130,8 @@ KDGanttMinimizeSplitter.cpp \
127 ktextedit.cpp \ 130 ktextedit.cpp \
128 ofileselector_p.cpp \ 131 ofileselector_p.cpp \
129 ofontselector.cpp \ 132 ofontselector.cpp \
133oprocctrl.cpp \
134oprocess.cpp \
130 kdecore/kcatalogue.cpp \ 135 kdecore/kcatalogue.cpp \
131 kdecore/klibloader.cpp \ 136 kdecore/klibloader.cpp \
132 kdecore/klocale.cpp \ 137 kdecore/klocale.cpp \
diff --git a/microkde/oprocctrl.cpp b/microkde/oprocctrl.cpp
new file mode 100644
index 0000000..404e0b3
--- a/dev/null
+++ b/microkde/oprocctrl.cpp
@@ -0,0 +1,285 @@
1/* This file is part of the KDE libraries
2 Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at)
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA.
18*/
19//
20// KPROCESSCONTROLLER -- A helper class for KProcess
21//
22// version 0.3.1, Jan, 8th 1997
23//
24// (C) Christian Czezatke
25// e9025461@student.tuwien.ac.at
26// Ported by Holger Freyther
27//
28
29//#include <config.h>
30
31#include <sys/types.h>
32#include <sys/socket.h>
33
34#include <errno.h>
35#include <fcntl.h>
36#include <stdio.h>
37#include <string.h>
38#include <unistd.h>
39#include <assert.h>
40
41#include <qsocketnotifier.h>
42#include "oprocctrl.h"
43
44using namespace Opie::Core::Internal;
45
46OProcessController *OProcessController::theOProcessController = 0;
47
48struct sigaction OProcessController::oldChildHandlerData;
49bool OProcessController::handlerSet = false;
50
51OProcessController::OProcessController()
52{
53 assert( theOProcessController == 0 );
54
55 if (0 > pipe(fd))
56 printf(strerror(errno));
57
58 notifier = new QSocketNotifier(fd[0], QSocketNotifier::Read);
59 notifier->setEnabled(true);
60 QObject::connect(notifier, SIGNAL(activated(int)),
61 this, SLOT(slotDoHousekeeping(int)));
62 connect( &delayedChildrenCleanupTimer, SIGNAL( timeout()),
63 SLOT( delayedChildrenCleanup()));
64
65 theOProcessController = this;
66
67 setupHandlers();
68}
69
70
71void OProcessController::setupHandlers()
72{
73 if( handlerSet )
74 return;
75 struct sigaction act;
76 act.sa_handler=theSigCHLDHandler;
77 sigemptyset(&(act.sa_mask));
78 sigaddset(&(act.sa_mask), SIGCHLD);
79 // Make sure we don't block this signal. gdb tends to do that :-(
80 sigprocmask(SIG_UNBLOCK, &(act.sa_mask), 0);
81
82 act.sa_flags = SA_NOCLDSTOP;
83
84 // CC: take care of SunOS which automatically restarts interrupted system
85 // calls (and thus does not have SA_RESTART)
86
87#ifdef SA_RESTART
88 act.sa_flags |= SA_RESTART;
89#endif
90
91 sigaction( SIGCHLD, &act, &oldChildHandlerData );
92
93 act.sa_handler=SIG_IGN;
94 sigemptyset(&(act.sa_mask));
95 sigaddset(&(act.sa_mask), SIGPIPE);
96 act.sa_flags = 0;
97 sigaction( SIGPIPE, &act, 0L);
98 handlerSet = true;
99}
100
101void OProcessController::resetHandlers()
102{
103 if( !handlerSet )
104 return;
105 sigaction( SIGCHLD, &oldChildHandlerData, 0 );
106 // there should be no problem with SIGPIPE staying SIG_IGN
107 handlerSet = false;
108}
109
110// block SIGCHLD handler, because it accesses processList
111void OProcessController::addOProcess( OProcess* p )
112{
113 sigset_t newset, oldset;
114 sigemptyset( &newset );
115 sigaddset( &newset, SIGCHLD );
116 sigprocmask( SIG_BLOCK, &newset, &oldset );
117 processList.append( p );
118 sigprocmask( SIG_SETMASK, &oldset, 0 );
119}
120
121void OProcessController::removeOProcess( OProcess* p )
122{
123 sigset_t newset, oldset;
124 sigemptyset( &newset );
125 sigaddset( &newset, SIGCHLD );
126 sigprocmask( SIG_BLOCK, &newset, &oldset );
127 processList.remove( p );
128 sigprocmask( SIG_SETMASK, &oldset, 0 );
129}
130
131//using a struct which contains both the pid and the status makes it easier to write
132//and read the data into the pipe
133//especially this solves a problem which appeared on my box where slotDoHouseKeeping() received
134//only 4 bytes (with some debug output around the write()'s it received all 8 bytes)
135//don't know why this happened, but when writing all 8 bytes at once it works here, aleXXX
136struct waitdata
137{
138 pid_t pid;
139 int status;
140};
141
142void OProcessController::theSigCHLDHandler(int arg)
143{
144 struct waitdata wd;
145 // int status;
146 // pid_t this_pid;
147 int saved_errno;
148
149 saved_errno = errno;
150 // since waitpid and write change errno, we have to save it and restore it
151 // (Richard Stevens, Advanced programming in the Unix Environment)
152
153 bool found = false;
154 if( theOProcessController != 0 )
155 {
156 // iterating the list doesn't perform any system call
157 for( QValueList<OProcess*>::ConstIterator it = theOProcessController->processList.begin();
158 it != theOProcessController->processList.end();
159 ++it )
160 {
161 if( !(*it)->isRunning())
162 continue;
163 wd.pid = waitpid( (*it)->pid(), &wd.status, WNOHANG );
164 if ( wd.pid > 0 )
165 {
166 ::write(theOProcessController->fd[1], &wd, sizeof(wd));
167 found = true;
168 }
169 }
170 }
171 if( !found && oldChildHandlerData.sa_handler != SIG_IGN
172 && oldChildHandlerData.sa_handler != SIG_DFL )
173 oldChildHandlerData.sa_handler( arg ); // call the old handler
174 // handle the rest
175 if( theOProcessController != 0 )
176 {
177 static const struct waitdata dwd = { 0, 0 }
178 ; // delayed waitpid()
179 ::write(theOProcessController->fd[1], &dwd, sizeof(dwd));
180 }
181 else
182 {
183 int dummy;
184 while( waitpid( -1, &dummy, WNOHANG ) > 0 )
185 ;
186 }
187
188 errno = saved_errno;
189}
190
191
192
193void OProcessController::slotDoHousekeeping(int )
194{
195 unsigned int bytes_read = 0;
196 unsigned int errcnt=0;
197 // read pid and status from the pipe.
198 struct waitdata wd;
199 while ((bytes_read < sizeof(wd)) && (errcnt < 50))
200 {
201 int r = ::read(fd[0], ((char *)&wd) + bytes_read, sizeof(wd) - bytes_read);
202 if (r > 0) bytes_read += r;
203 else if (r < 0) errcnt++;
204 }
205 if (errcnt >= 50)
206 {
207 fprintf(stderr,
208 "Error: Max. error count for pipe read "
209 "exceeded in OProcessController::slotDoHousekeeping\n");
210 return; // it makes no sense to continue here!
211 }
212 if (bytes_read != sizeof(wd))
213 {
214 fprintf(stderr,
215 "Error: Could not read info from signal handler %d <> %d!\n",
216 bytes_read, sizeof(wd));
217 return; // it makes no sense to continue here!
218 }
219 if (wd.pid==0)
220 { // special case, see delayedChildrenCleanup()
221 delayedChildrenCleanupTimer.start( 1000, true );
222 return;
223 }
224
225 for( QValueList<OProcess*>::ConstIterator it = processList.begin();
226 it != processList.end();
227 ++it )
228 {
229 OProcess* proc = *it;
230 if (proc->pid() == wd.pid)
231 {
232 // process has exited, so do emit the respective events
233 if (proc->run_mode == OProcess::Block)
234 {
235 // If the reads are done blocking then set the status in proc
236 // but do nothing else because OProcess will perform the other
237 // actions of processHasExited.
238 proc->status = wd.status;
239 proc->runs = false;
240 }
241 else
242 {
243 proc->processHasExited(wd.status);
244 }
245 return;
246 }
247 }
248}
249
250// this is needed e.g. for popen(), which calls waitpid() checking
251// for its forked child, if we did waitpid() directly in the SIGCHLD
252// handler, popen()'s waitpid() call would fail
253void OProcessController::delayedChildrenCleanup()
254{
255 struct waitdata wd;
256 while(( wd.pid = waitpid( -1, &wd.status, WNOHANG ) ) > 0 )
257 {
258 for( QValueList<OProcess*>::ConstIterator it = processList.begin();
259 it != processList.end();
260 ++it )
261 {
262 if( !(*it)->isRunning() || (*it)->pid() != wd.pid )
263 continue;
264 // it's OProcess, handle it
265 ::write(fd[1], &wd, sizeof(wd));
266 break;
267 }
268 }
269}
270
271OProcessController::~OProcessController()
272{
273 assert( theOProcessController == this );
274 resetHandlers();
275
276 notifier->setEnabled(false);
277
278 close(fd[0]);
279 close(fd[1]);
280
281 delete notifier;
282 theOProcessController = 0;
283}
284
285//#include "kprocctrl.moc"
diff --git a/microkde/oprocctrl.h b/microkde/oprocctrl.h
new file mode 100644
index 0000000..ea00859
--- a/dev/null
+++ b/microkde/oprocctrl.h
@@ -0,0 +1,129 @@
1/* This file is part of the KDE libraries
2 Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at)
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA.
18*/
19//
20// KPROCESSCONTROLLER -- A helper class for KProcess
21//
22// version 0.3.1, Jan 8th 1997
23//
24// (C) Christian Czezatke
25// e9025461@student.tuwien.ac.at
26// Ported by Holger Freyther
27//
28
29#ifndef __KPROCCTRL_H__
30#define __KPROCCTRL_H__
31
32#include <qvaluelist.h>
33#include <qtimer.h>
34
35#include "oprocess.h"
36
37class QSocketNotifier;
38
39
40namespace Opie {
41namespace Core {
42namespace Internal {
43class OProcessControllerPrivate;
44
45/**
46 * @short Used internally by @ref OProcess
47 * @internal
48 * @author Christian Czezakte <e9025461@student.tuwien.ac.at>
49 *
50 * A class for internal use by OProcess only. -- Exactly one instance
51 * of this class is generated by the first instance of OProcess that is
52 * created (a pointer to it gets stored in @ref theOProcessController ).
53 *
54 * This class takes care of the actual (UN*X) signal handling.
55*/
56class OProcessController : public QObject
57{
58 Q_OBJECT
59
60public:
61 OProcessController();
62 ~OProcessController();
63 //CC: WARNING! Destructor Not virtual (but you don't derive classes from this anyhow...)
64
65public:
66
67 /**
68 * Only a single instance of this class is allowed at a time,
69 * and this static variable is used to track the one instance.
70 */
71 static OProcessController *theOProcessController;
72
73 /**
74 * Automatically called upon SIGCHLD.
75 *
76 * Normally you do not need to do anything with this function but
77 * if your application needs to disable SIGCHLD for some time for
78 * reasons beyond your control, you should call this function afterwards
79 * to make sure that no SIGCHLDs where missed.
80 */
81 static void theSigCHLDHandler(int signal);
82 // handler for sigchld
83
84 /**
85 * @internal
86 */
87 static void setupHandlers();
88 /**
89 * @internal
90 */
91 static void resetHandlers();
92 /**
93 * @internal
94 */
95 void addOProcess( OProcess* );
96 /**
97 * @internal
98 */
99 void removeOProcess( OProcess* );
100public slots:
101 /**
102 * @internal
103 */
104 void slotDoHousekeeping(int socket);
105
106private slots:
107 void delayedChildrenCleanup();
108private:
109 int fd[2];
110 QSocketNotifier *notifier;
111 static struct sigaction oldChildHandlerData;
112 static bool handlerSet;
113 QValueList<OProcess*> processList;
114 QTimer delayedChildrenCleanupTimer;
115
116 // Disallow assignment and copy-construction
117 OProcessController( const OProcessController& );
118 OProcessController& operator= ( const OProcessController& );
119
120 OProcessControllerPrivate *d;
121};
122
123}
124}
125}
126
127
128#endif
129
diff --git a/microkde/oprocess.cpp b/microkde/oprocess.cpp
new file mode 100644
index 0000000..95e3e4b
--- a/dev/null
+++ b/microkde/oprocess.cpp
@@ -0,0 +1,951 @@
1/*
2                This file is part of the Opie Project
3             Copyright (C) 2002-2004 Holger Freyther <zecke@handhelds.org>
4 and The Opie Team <opie-devel@handhelds.org>
5 =. Based on KProcess (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at)
6 .=l.
7          .>+-=
8_;:,     .>    :=|. This program is free software; you can
9.> <`_,   >  .   <= redistribute it and/or modify it under
10:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
11.="- .-=="i,     .._ License as published by the Free Software
12- .   .-<_>     .<> Foundation; either version 2 of the License,
13    ._= =}       : or (at your option) any later version.
14   .%`+i>       _;_.
15   .i_,=:_.      -<s. This program is distributed in the hope that
16    +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
17   : ..    .:,     . . . without even the implied warranty of
18   =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
19 _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
20..}^=.=       =       ; Library General Public License for more
21++=   -.     .`     .: details.
22:     =  ...= . :.=-
23-.   .:....=;==+<; You should have received a copy of the GNU
24 -_. . .   )=.  = Library General Public License along with
25   --        :-=` this library; see the file COPYING.LIB.
26 If not, write to the Free Software Foundation,
27 Inc., 59 Temple Place - Suite 330,
28 Boston, MA 02111-1307, USA.
29*/
30
31#include "oprocctrl.h"
32
33/* OPIE */
34#include <oprocess.h>
35
36/* QT */
37
38#include <qapplication.h>
39#include <qdir.h>
40#include <qmap.h>
41#include <qsocketnotifier.h>
42#include <qtextstream.h>
43
44/* STD */
45#include <errno.h>
46#include <fcntl.h>
47#include <pwd.h>
48#include <stdlib.h>
49#include <signal.h>
50#include <stdio.h>
51#include <string.h>
52#include <sys/time.h>
53#include <sys/types.h>
54#include <sys/stat.h>
55#include <sys/socket.h>
56#include <unistd.h>
57#ifdef HAVE_SYS_SELECT_H
58#include <sys/select.h>
59#endif
60#ifdef HAVE_INITGROUPS
61#include <grp.h>
62#endif
63
64using namespace Opie::Core::Internal;
65
66namespace Opie {
67namespace Core {
68namespace Internal {
69class OProcessPrivate
70{
71public:
72 OProcessPrivate() : useShell( false )
73 { }
74
75 bool useShell;
76 QMap<QString, QString> env;
77 QString wd;
78 QCString shell;
79};
80}
81
82OProcess::OProcess( QObject *parent, const char *name )
83 : QObject( parent, name )
84{
85 init ( );
86}
87
88OProcess::OProcess( const QString &arg0, QObject *parent, const char *name )
89 : QObject( parent, name )
90{
91 init ( );
92 *this << arg0;
93}
94
95OProcess::OProcess( const QStringList &args, QObject *parent, const char *name )
96 : QObject( parent, name )
97{
98 init ( );
99 *this << args;
100}
101
102void OProcess::init ( )
103{
104 run_mode = NotifyOnExit;
105 runs = false;
106 pid_ = 0;
107 status = 0;
108 keepPrivs = false;
109 innot = 0;
110 outnot = 0;
111 errnot = 0;
112 communication = NoCommunication;
113 input_data = 0;
114 input_sent = 0;
115 input_total = 0;
116 d = 0;
117
118 if ( 0 == OProcessController::theOProcessController )
119 {
120 ( void ) new OProcessController();
121 CHECK_PTR( OProcessController::theOProcessController );
122 }
123
124 OProcessController::theOProcessController->addOProcess( this );
125 out[ 0 ] = out[ 1 ] = -1;
126 in[ 0 ] = in[ 1 ] = -1;
127 err[ 0 ] = err[ 1 ] = -1;
128}
129
130void OProcess::setEnvironment( const QString &name, const QString &value )
131{
132 if ( !d )
133 d = new OProcessPrivate;
134 d->env.insert( name, value );
135}
136
137void OProcess::setWorkingDirectory( const QString &dir )
138{
139 if ( !d )
140 d = new OProcessPrivate;
141 d->wd = dir;
142}
143
144void OProcess::setupEnvironment()
145{
146 if ( d )
147 {
148 QMap<QString, QString>::Iterator it;
149 for ( it = d->env.begin(); it != d->env.end(); ++it )
150 setenv( QFile::encodeName( it.key() ).data(),
151 QFile::encodeName( it.data() ).data(), 1 );
152 if ( !d->wd.isEmpty() )
153 chdir( QFile::encodeName( d->wd ).data() );
154 }
155}
156
157void OProcess::setRunPrivileged( bool keepPrivileges )
158{
159 keepPrivs = keepPrivileges;
160}
161
162bool OProcess::runPrivileged() const
163{
164 return keepPrivs;
165}
166
167OProcess::~OProcess()
168{
169 // destroying the OProcess instance sends a SIGKILL to the
170 // child process (if it is running) after removing it from the
171 // list of valid processes (if the process is not started as
172 // "DontCare")
173
174 OProcessController::theOProcessController->removeOProcess( this );
175 // this must happen before we kill the child
176 // TODO: block the signal while removing the current process from the process list
177
178 if ( runs && ( run_mode != DontCare ) )
179 kill( SIGKILL );
180
181 // Clean up open fd's and socket notifiers.
182 closeStdin();
183 closeStdout();
184 closeStderr();
185
186 // TODO: restore SIGCHLD and SIGPIPE handler if this is the last OProcess
187 delete d;
188}
189
190void OProcess::detach()
191{
192 OProcessController::theOProcessController->removeOProcess( this );
193
194 runs = false;
195 pid_ = 0;
196
197 // Clean up open fd's and socket notifiers.
198 closeStdin();
199 closeStdout();
200 closeStderr();
201}
202
203bool OProcess::setExecutable( const QString& proc )
204{
205 if ( runs )
206 return false;
207
208 if ( proc.isEmpty() )
209 return false;
210
211 if ( !arguments.isEmpty() )
212 arguments.remove( arguments.begin() );
213 arguments.prepend( QFile::encodeName( proc ) );
214
215 return true;
216}
217
218OProcess &OProcess::operator<<( const QStringList& args )
219{
220 QStringList::ConstIterator it = args.begin();
221 for ( ; it != args.end() ; ++it )
222 arguments.append( QFile::encodeName( *it ) );
223 return *this;
224}
225
226OProcess &OProcess::operator<<( const QCString& arg )
227{
228 return operator<< ( arg.data() );
229}
230
231OProcess &OProcess::operator<<( const char* arg )
232{
233 arguments.append( arg );
234 return *this;
235}
236
237OProcess &OProcess::operator<<( const QString& arg )
238{
239 arguments.append( QFile::encodeName( arg ) );
240 return *this;
241}
242
243void OProcess::clearArguments()
244{
245 arguments.clear();
246}
247
248bool OProcess::start( RunMode runmode, Communication comm )
249{
250 uint i;
251 uint n = arguments.count();
252 char **arglist;
253
254 if ( runs || ( 0 == n ) )
255 {
256 return false; // cannot start a process that is already running
257 // or if no executable has been assigned
258 }
259 run_mode = runmode;
260 status = 0;
261
262 QCString shellCmd;
263 if ( d && d->useShell )
264 {
265 if ( d->shell.isEmpty() )
266 {
267 qWarning( "Could not find a valid shell" );
268 return false;
269 }
270
271 arglist = static_cast<char **>( malloc( ( 4 ) * sizeof( char * ) ) );
272 for ( i = 0; i < n; i++ )
273 {
274 shellCmd += arguments[ i ];
275 shellCmd += " "; // CC: to separate the arguments
276 }
277
278 arglist[ 0 ] = d->shell.data();
279 arglist[ 1 ] = ( char * ) "-c";
280 arglist[ 2 ] = shellCmd.data();
281 arglist[ 3 ] = 0;
282 }
283 else
284 {
285 arglist = static_cast<char **>( malloc( ( n + 1 ) * sizeof( char * ) ) );
286 for ( i = 0; i < n; i++ )
287 arglist[ i ] = arguments[ i ].data();
288 arglist[ n ] = 0;
289 }
290
291 if ( !setupCommunication( comm ) )
292 qWarning( "Could not setup Communication!" );
293
294 // We do this in the parent because if we do it in the child process
295 // gdb gets confused when the application runs from gdb.
296 uid_t uid = getuid();
297 gid_t gid = getgid();
298#ifdef HAVE_INITGROUPS
299
300 struct passwd *pw = getpwuid( uid );
301#endif
302
303 int fd[ 2 ];
304 if ( 0 > pipe( fd ) )
305 {
306 fd[ 0 ] = fd[ 1 ] = 0; // Pipe failed.. continue
307 }
308
309 runs = true;
310
311 QApplication::flushX();
312
313 // WABA: Note that we use fork() and not vfork() because
314 // vfork() has unclear semantics and is not standardized.
315 pid_ = fork();
316
317 if ( 0 == pid_ )
318 {
319 if ( fd[ 0 ] )
320 close( fd[ 0 ] );
321 if ( !runPrivileged() )
322 {
323 setgid( gid );
324#if defined( HAVE_INITGROUPS)
325
326 if ( pw )
327 initgroups( pw->pw_name, pw->pw_gid );
328#endif
329
330 setuid( uid );
331 }
332 // The child process
333 if ( !commSetupDoneC() )
334 qWarning( "Could not finish comm setup in child!" );
335
336 setupEnvironment();
337
338 // Matthias
339 if ( run_mode == DontCare )
340 setpgid( 0, 0 );
341 // restore default SIGPIPE handler (Harri)
342 struct sigaction act;
343 sigemptyset( &( act.sa_mask ) );
344 sigaddset( &( act.sa_mask ), SIGPIPE );
345 act.sa_handler = SIG_DFL;
346 act.sa_flags = 0;
347 sigaction( SIGPIPE, &act, 0L );
348
349 // We set the close on exec flag.
350 // Closing of fd[1] indicates that the execvp succeeded!
351 if ( fd[ 1 ] )
352 fcntl( fd[ 1 ], F_SETFD, FD_CLOEXEC );
353 execvp( arglist[ 0 ], arglist );
354 char resultByte = 1;
355 if ( fd[ 1 ] )
356 write( fd[ 1 ], &resultByte, 1 );
357 _exit( -1 );
358 }
359 else if ( -1 == pid_ )
360 {
361 // forking failed
362
363 runs = false;
364 free( arglist );
365 return false;
366 }
367 else
368 {
369 if ( fd[ 1 ] )
370 close( fd[ 1 ] );
371 // the parent continues here
372
373 // Discard any data for stdin that might still be there
374 input_data = 0;
375
376 // Check whether client could be started.
377 if ( fd[ 0 ] )
378 for ( ;; )
379 {
380 char resultByte;
381 int n = ::read( fd[ 0 ], &resultByte, 1 );
382 if ( n == 1 )
383 {
384 // Error
385 runs = false;
386 close( fd[ 0 ] );
387 free( arglist );
388 pid_ = 0;
389 return false;
390 }
391 if ( n == -1 )
392 {
393 if ( ( errno == ECHILD ) || ( errno == EINTR ) )
394 continue; // Ignore
395 }
396 break; // success
397 }
398 if ( fd[ 0 ] )
399 close( fd[ 0 ] );
400
401 if ( !commSetupDoneP() ) // finish communication socket setup for the parent
402 qWarning( "Could not finish comm setup in parent!" );
403
404 if ( run_mode == Block )
405 {
406 commClose();
407
408 // The SIGCHLD handler of the process controller will catch
409 // the exit and set the status
410 while ( runs )
411 {
412 OProcessController::theOProcessController->
413 slotDoHousekeeping( 0 );
414 }
415 runs = FALSE;
416 emit processExited( this );
417 }
418 }
419 free( arglist );
420 return true;
421}
422
423
424
425bool OProcess::kill( int signo )
426{
427 bool rv = false;
428
429 if ( 0 != pid_ )
430 rv = ( -1 != ::kill( pid_, signo ) );
431 // probably store errno somewhere...
432 return rv;
433}
434
435bool OProcess::isRunning() const
436{
437 return runs;
438}
439
440pid_t OProcess::pid() const
441{
442 return pid_;
443}
444
445bool OProcess::normalExit() const
446{
447 int _status = status;
448 return ( pid_ != 0 ) && ( !runs ) && ( WIFEXITED( ( _status ) ) );
449}
450
451int OProcess::exitStatus() const
452{
453 int _status = status;
454 return WEXITSTATUS( ( _status ) );
455}
456
457bool OProcess::writeStdin( const char *buffer, int buflen )
458{
459 bool rv;
460
461 // if there is still data pending, writing new data
462 // to stdout is not allowed (since it could also confuse
463 // kprocess...
464 if ( 0 != input_data )
465 return false;
466
467 if ( runs && ( communication & Stdin ) )
468 {
469 input_data = buffer;
470 input_sent = 0;
471 input_total = buflen;
472 slotSendData( 0 );
473 innot->setEnabled( true );
474 rv = true;
475 }
476 else
477 rv = false;
478 return rv;
479}
480
481void OProcess::flushStdin ( )
482{
483 if ( !input_data || ( input_sent == input_total ) )
484 return ;
485
486 int d1, d2;
487
488 do
489 {
490 d1 = input_total - input_sent;
491 slotSendData ( 0 );
492 d2 = input_total - input_sent;
493 }
494 while ( d2 <= d1 );
495}
496
497void OProcess::suspend()
498{
499 if ( ( communication & Stdout ) && outnot )
500 outnot->setEnabled( false );
501}
502
503void OProcess::resume()
504{
505 if ( ( communication & Stdout ) && outnot )
506 outnot->setEnabled( true );
507}
508
509bool OProcess::closeStdin()
510{
511 bool rv;
512
513 if ( communication & Stdin )
514 {
515 communication = ( Communication ) ( communication & ~Stdin );
516 delete innot;
517 innot = 0;
518 close( in[ 1 ] );
519 rv = true;
520 }
521 else
522 rv = false;
523 return rv;
524}
525
526bool OProcess::closeStdout()
527{
528 bool rv;
529
530 if ( communication & Stdout )
531 {
532 communication = ( Communication ) ( communication & ~Stdout );
533 delete outnot;
534 outnot = 0;
535 close( out[ 0 ] );
536 rv = true;
537 }
538 else
539 rv = false;
540 return rv;
541}
542
543bool OProcess::closeStderr()
544{
545 bool rv;
546
547 if ( communication & Stderr )
548 {
549 communication = static_cast<Communication>( communication & ~Stderr );
550 delete errnot;
551 errnot = 0;
552 close( err[ 0 ] );
553 rv = true;
554 }
555 else
556 rv = false;
557 return rv;
558}
559
560void OProcess::slotChildOutput( int fdno )
561{
562 if ( !childOutput( fdno ) )
563 closeStdout();
564}
565
566void OProcess::slotChildError( int fdno )
567{
568 if ( !childError( fdno ) )
569 closeStderr();
570}
571
572void OProcess::slotSendData( int )
573{
574 if ( input_sent == input_total )
575 {
576 innot->setEnabled( false );
577 input_data = 0;
578 emit wroteStdin( this );
579 }
580 else
581 input_sent += ::write( in[ 1 ], input_data + input_sent, input_total - input_sent );
582}
583
584void OProcess::processHasExited( int state )
585{
586 if ( runs )
587 {
588 runs = false;
589 status = state;
590
591 commClose(); // cleanup communication sockets
592
593 // also emit a signal if the process was run Blocking
594 if ( DontCare != run_mode )
595 {
596 emit processExited( this );
597 }
598 }
599}
600
601int OProcess::childOutput( int fdno )
602{
603 if ( communication & NoRead )
604 {
605 int len = -1;
606 emit receivedStdout( fdno, len );
607 errno = 0; // Make sure errno doesn't read "EAGAIN"
608 return len;
609 }
610 else
611 {
612 char buffer[ 1024 ];
613 int len;
614
615 len = ::read( fdno, buffer, 1024 );
616
617 if ( 0 < len )
618 {
619 emit receivedStdout( this, buffer, len );
620 }
621 return len;
622 }
623}
624
625int OProcess::childError( int fdno )
626{
627 char buffer[ 1024 ];
628 int len;
629
630 len = ::read( fdno, buffer, 1024 );
631
632 if ( 0 < len )
633 emit receivedStderr( this, buffer, len );
634 return len;
635}
636
637int OProcess::setupCommunication( Communication comm )
638{
639 int ok;
640
641 communication = comm;
642
643 ok = 1;
644 if ( comm & Stdin )
645 ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, in ) >= 0;
646
647 if ( comm & Stdout )
648 ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, out ) >= 0;
649
650 if ( comm & Stderr )
651 ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, err ) >= 0;
652
653 return ok;
654}
655
656int OProcess::commSetupDoneP()
657{
658 int ok = 1;
659
660 if ( communication != NoCommunication )
661 {
662 if ( communication & Stdin )
663 close( in[ 0 ] );
664 if ( communication & Stdout )
665 close( out[ 1 ] );
666 if ( communication & Stderr )
667 close( err[ 1 ] );
668
669 // Don't create socket notifiers and set the sockets non-blocking if
670 // blocking is requested.
671 if ( run_mode == Block )
672 return ok;
673
674 if ( communication & Stdin )
675 {
676 // ok &= (-1 != fcntl(in[1], F_SETFL, O_NONBLOCK));
677 innot = new QSocketNotifier( in[ 1 ], QSocketNotifier::Write, this );
678 CHECK_PTR( innot );
679 innot->setEnabled( false ); // will be enabled when data has to be sent
680 QObject::connect( innot, SIGNAL( activated(int) ),
681 this, SLOT( slotSendData(int) ) );
682 }
683
684 if ( communication & Stdout )
685 {
686 // ok &= (-1 != fcntl(out[0], F_SETFL, O_NONBLOCK));
687 outnot = new QSocketNotifier( out[ 0 ], QSocketNotifier::Read, this );
688 CHECK_PTR( outnot );
689 QObject::connect( outnot, SIGNAL( activated(int) ),
690 this, SLOT( slotChildOutput(int) ) );
691 if ( communication & NoRead )
692 suspend();
693 }
694
695 if ( communication & Stderr )
696 {
697 // ok &= (-1 != fcntl(err[0], F_SETFL, O_NONBLOCK));
698 errnot = new QSocketNotifier( err[ 0 ], QSocketNotifier::Read, this );
699 CHECK_PTR( errnot );
700 QObject::connect( errnot, SIGNAL( activated(int) ),
701 this, SLOT( slotChildError(int) ) );
702 }
703 }
704 return ok;
705}
706
707int OProcess::commSetupDoneC()
708{
709 int ok = 1;
710 struct linger so;
711 memset( &so, 0, sizeof( so ) );
712
713 if ( communication & Stdin )
714 close( in[ 1 ] );
715 if ( communication & Stdout )
716 close( out[ 0 ] );
717 if ( communication & Stderr )
718 close( err[ 0 ] );
719
720 if ( communication & Stdin )
721 ok &= dup2( in[ 0 ], STDIN_FILENO ) != -1;
722 else
723 {
724 int null_fd = open( "/dev/null", O_RDONLY );
725 ok &= dup2( null_fd, STDIN_FILENO ) != -1;
726 close( null_fd );
727 }
728 if ( communication & Stdout )
729 {
730 ok &= dup2( out[ 1 ], STDOUT_FILENO ) != -1;
731 ok &= !setsockopt( out[ 1 ], SOL_SOCKET, SO_LINGER, ( char* ) & so, sizeof( so ) );
732 }
733 else
734 {
735 int null_fd = open( "/dev/null", O_WRONLY );
736 ok &= dup2( null_fd, STDOUT_FILENO ) != -1;
737 close( null_fd );
738 }
739 if ( communication & Stderr )
740 {
741 ok &= dup2( err[ 1 ], STDERR_FILENO ) != -1;
742 ok &= !setsockopt( err[ 1 ], SOL_SOCKET, SO_LINGER, reinterpret_cast<char *>( &so ), sizeof( so ) );
743 }
744 else
745 {
746 int null_fd = open( "/dev/null", O_WRONLY );
747 ok &= dup2( null_fd, STDERR_FILENO ) != -1;
748 close( null_fd );
749 }
750 return ok;
751}
752
753void OProcess::commClose()
754{
755 if ( NoCommunication != communication )
756 {
757 bool b_in = ( communication & Stdin );
758 bool b_out = ( communication & Stdout );
759 bool b_err = ( communication & Stderr );
760 if ( b_in )
761 delete innot;
762
763 if ( b_out || b_err )
764 {
765 // If both channels are being read we need to make sure that one socket buffer
766 // doesn't fill up whilst we are waiting for data on the other (causing a deadlock).
767 // Hence we need to use select.
768
769 // Once one or other of the channels has reached EOF (or given an error) go back
770 // to the usual mechanism.
771
772 int fds_ready = 1;
773 fd_set rfds;
774
775 int max_fd = 0;
776 if ( b_out )
777 {
778 fcntl( out[ 0 ], F_SETFL, O_NONBLOCK );
779 if ( out[ 0 ] > max_fd )
780 max_fd = out[ 0 ];
781 delete outnot;
782 outnot = 0;
783 }
784 if ( b_err )
785 {
786 fcntl( err[ 0 ], F_SETFL, O_NONBLOCK );
787 if ( err[ 0 ] > max_fd )
788 max_fd = err[ 0 ];
789 delete errnot;
790 errnot = 0;
791 }
792
793
794 while ( b_out || b_err )
795 {
796 // * If the process is still running we block until we
797 // receive data. (p_timeout = 0, no timeout)
798 // * If the process has already exited, we only check
799 // the available data, we don't wait for more.
800 // (p_timeout = &timeout, timeout immediately)
801 struct timeval timeout;
802 timeout.tv_sec = 0;
803 timeout.tv_usec = 0;
804 struct timeval *p_timeout = runs ? 0 : &timeout;
805
806 FD_ZERO( &rfds );
807 if ( b_out )
808 FD_SET( out[ 0 ], &rfds );
809
810 if ( b_err )
811 FD_SET( err[ 0 ], &rfds );
812
813 fds_ready = select( max_fd + 1, &rfds, 0, 0, p_timeout );
814 if ( fds_ready <= 0 )
815 break;
816
817 if ( b_out && FD_ISSET( out[ 0 ], &rfds ) )
818 {
819 int ret = 1;
820 while ( ret > 0 )
821 ret = childOutput( out[ 0 ] );
822 if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 )
823 b_out = false;
824 }
825
826 if ( b_err && FD_ISSET( err[ 0 ], &rfds ) )
827 {
828 int ret = 1;
829 while ( ret > 0 )
830 ret = childError( err[ 0 ] );
831 if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 )
832 b_err = false;
833 }
834 }
835 }
836
837 if ( b_in )
838 {
839 communication = ( Communication ) ( communication & ~Stdin );
840 close( in[ 1 ] );
841 }
842 if ( b_out )
843 {
844 communication = ( Communication ) ( communication & ~Stdout );
845 close( out[ 0 ] );
846 }
847 if ( b_err )
848 {
849 communication = ( Communication ) ( communication & ~Stderr );
850 close( err[ 0 ] );
851 }
852 }
853}
854
855void OProcess::setUseShell( bool useShell, const char *shell )
856{
857 if ( !d )
858 d = new OProcessPrivate;
859 d->useShell = useShell;
860 d->shell = shell;
861 if ( d->shell.isEmpty() )
862 d->shell = searchShell();
863}
864
865QString OProcess::quote( const QString &arg )
866{
867 QString res = arg;
868 res.replace( QRegExp( QString::fromLatin1( "\'" ) ),
869 QString::fromLatin1( "'\"'\"'" ) );
870 res.prepend( '\'' );
871 res.append( '\'' );
872 return res;
873}
874
875QCString OProcess::searchShell()
876{
877 QCString tmpShell = QCString( getenv( "SHELL" ) ).stripWhiteSpace();
878 if ( !isExecutable( tmpShell ) )
879 {
880 tmpShell = "/bin/sh";
881 }
882
883 return tmpShell;
884}
885
886bool OProcess::isExecutable( const QCString &filename )
887{
888 struct stat fileinfo;
889
890 if ( filename.isEmpty() )
891 return false;
892
893 // CC: we've got a valid filename, now let's see whether we can execute that file
894
895 if ( -1 == stat( filename.data(), &fileinfo ) )
896 return false;
897 // CC: return false if the file does not exist
898
899 // CC: anyway, we cannot execute directories, block/character devices, fifos or sockets
900 if ( ( S_ISDIR( fileinfo.st_mode ) ) ||
901 ( S_ISCHR( fileinfo.st_mode ) ) ||
902 ( S_ISBLK( fileinfo.st_mode ) ) ||
903#ifdef S_ISSOCK
904 // CC: SYSVR4 systems don't have that macro
905 ( S_ISSOCK( fileinfo.st_mode ) ) ||
906#endif
907 ( S_ISFIFO( fileinfo.st_mode ) ) ||
908 ( S_ISDIR( fileinfo.st_mode ) ) )
909 {
910 return false;
911 }
912
913 // CC: now check for permission to execute the file
914 if ( access( filename.data(), X_OK ) != 0 )
915 return false;
916
917 // CC: we've passed all the tests...
918 return true;
919}
920
921int OProcess::processPID( const QString& process )
922{
923 QString line;
924 QDir d = QDir( "/proc" );
925 QStringList dirs = d.entryList( QDir::Dirs );
926 QStringList::Iterator it;
927 for ( it = dirs.begin(); it != dirs.end(); ++it )
928 {
929 //qDebug( "next entry: %s", (const char*) *it );
930 QFile file( "/proc/"+*it+"/cmdline" );
931 file.open( IO_ReadOnly );
932 if ( !file.isOpen() ) continue;
933 QTextStream t( &file );
934 line = t.readLine();
935 //qDebug( "cmdline = %s", (const char*) line );
936 if ( line.contains( process ) ) break; //FIXME: That may find also other process, if the name is not long enough ;)
937 }
938 if ( line.contains( process ) )
939 {
940 //qDebug( "found process id #%d", (*it).toInt() );
941 return (*it).toInt();
942 }
943 else
944 {
945 //qDebug( "process '%s' not found", (const char*) process );
946 return 0;
947 }
948}
949
950}
951}
diff --git a/microkde/oprocess.h b/microkde/oprocess.h
new file mode 100644
index 0000000..be1436c
--- a/dev/null
+++ b/microkde/oprocess.h
@@ -0,0 +1,761 @@
1/*
2                This file is part of the Opie Project
3             Copyright (C) 2003-2004 Holger Freyther <zecke@handhelds.org>
4 Copyright (C) The Opie Team <opie-devel@handhelds.org>
5 =. Based on KProcess (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at)
6 .=l.
7          .>+-=
8_;:,     .>    :=|. This program is free software; you can
9.> <`_,   >  .   <= redistribute it and/or modify it under
10:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
11.="- .-=="i,     .._ License as published by the Free Software
12- .   .-<_>     .<> Foundation; either version 2 of the License,
13    ._= =}       : or (at your option) any later version.
14   .%`+i>       _;_.
15   .i_,=:_.      -<s. This program is distributed in the hope that
16    +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
17   : ..    .:,     . . . without even the implied warranty of
18   =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
19 _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
20..}^=.=       =       ; Library General Public License for more
21++=   -.     .`     .: details.
22:     =  ...= . :.=-
23-.   .:....=;==+<; You should have received a copy of the GNU
24 -_. . .   )=.  = Library General Public License along with
25   --        :-=` this library; see the file COPYING.LIB.
26 If not, write to the Free Software Foundation,
27 Inc., 59 Temple Place - Suite 330,
28 Boston, MA 02111-1307, USA.
29*/
30
31#ifndef OPROCESS_H
32#define OPROCESS_H
33
34/* QT */
35#include <qcstring.h>
36#include <qobject.h>
37#include <qvaluelist.h>
38
39/* STD */
40#include <sys/types.h> // for pid_t
41#include <sys/wait.h>
42#include <signal.h>
43#include <unistd.h>
44
45class QSocketNotifier;
46
47namespace Opie {
48namespace Core {
49namespace Internal {
50class OProcessController;
51class OProcessPrivate;
52}
53
54/**
55 * Child process invocation, monitoring and control.
56 *
57 * @sect General usage and features
58 *
59 *This class allows a KDE and OPIE application to start child processes without having
60 *to worry about UN*X signal handling issues and zombie process reaping.
61 *
62 *@see KProcIO
63 *
64 *Basically, this class distinguishes three different ways of running
65 *child processes:
66 *
67 *@li OProcess::DontCare -- The child process is invoked and both the child
68 *process and the parent process continue concurrently.
69 *
70 *Starting a DontCare child process means that the application is
71 *not interested in any notification to determine whether the
72 *child process has already exited or not.
73 *
74 *@li OProcess::NotifyOnExit -- The child process is invoked and both the
75 *child and the parent process run concurrently.
76 *
77 *When the child process exits, the OProcess instance
78 *corresponding to it emits the Qt signal @ref processExited().
79 *
80 *Since this signal is @em not emitted from within a UN*X
81 *signal handler, arbitrary function calls can be made.
82 *
83 *Be aware: When the OProcess objects gets destructed, the child
84 *process will be killed if it is still running!
85 *This means in particular, that you cannot use a OProcess on the stack
86 *with OProcess::NotifyOnExit.
87 *
88 *@li OProcess::Block -- The child process starts and the parent process
89 *is suspended until the child process exits. (@em Really not recommended
90 *for programs with a GUI.)
91 *
92 *OProcess also provides several functions for determining the exit status
93 *and the pid of the child process it represents.
94 *
95 *Furthermore it is possible to supply command-line arguments to the process
96 *in a clean fashion (no null -- terminated stringlists and such...)
97 *
98 *A small usage example:
99 *<pre>
100 *OProcess *proc = new OProcess;
101 *
102 **proc << "my_executable";
103 **proc << "These" << "are" << "the" << "command" << "line" << "args";
104 *QApplication::connect(proc, SIGNAL(processExited(Opie::Core::OProcess *)),
105 * pointer_to_my_object, SLOT(my_objects_slot(Opie::Core::OProcess *)));
106 *proc->start();
107 *</pre>
108 *
109 *This will start "my_executable" with the commandline arguments "These"...
110 *
111 *When the child process exits, the respective Qt signal will be emitted.
112 *
113 *@sect Communication with the child process
114 *
115 *OProcess supports communication with the child process through
116 *stdin/stdout/stderr.
117 *
118 *The following functions are provided for getting data from the child
119 *process or sending data to the child's stdin (For more information,
120 *have a look at the documentation of each function):
121 *
122 *@li bool @ref writeStdin(char *buffer, int buflen);
123 *@li -- Transmit data to the child process's stdin.
124 *
125 *@li bool @ref closeStdin();
126 *@li -- Closes the child process's stdin (which causes it to see an feof(stdin)).
127 *Returns false if you try to close stdin for a process that has been started
128 *without a communication channel to stdin.
129 *
130 *@li bool @ref closeStdout();
131 *@li -- Closes the child process's stdout.
132 *Returns false if you try to close stdout for a process that has been started
133 *without a communication channel to stdout.
134 *
135 *@li bool @ref closeStderr();
136 *@li -- Closes the child process's stderr.
137 *Returns false if you try to close stderr for a process that has been started
138 *without a communication channel to stderr.
139 *
140 *
141 *@sect QT signals:
142 *
143 *@li void @ref receivedStdout(OProcess *proc, char *buffer, int buflen);
144 *@li void @ref receivedStderr(OProcess *proc, char *buffer, int buflen);
145 *@li -- Indicates that new data has arrived from either the
146 *child process's stdout or stderr.
147 *
148 *@li void @ref wroteStdin(OProcess *proc);
149 *@li -- Indicates that all data that has been sent to the child process
150 *by a prior call to @ref writeStdin() has actually been transmitted to the
151 *client .
152 *
153 *@author Christian Czezakte e9025461@student.tuwien.ac.at
154 *@author Holger Freyther (Opie Port)
155 *
156 **/
157class OProcess : public QObject
158{
159 Q_OBJECT
160
161public:
162
163 /**
164 * Modes in which the communication channel can be opened.
165 *
166 * If communication for more than one channel is required,
167 * the values have to be or'ed together, for example to get
168 * communication with stdout as well as with stdin, you would
169 * specify @p Stdin @p | @p Stdout
170 *
171 * If @p NoRead is specified in conjunction with @p Stdout,
172 * no data is actually read from @p Stdout but only
173 * the signal @ref childOutput(int fd) is emitted.
174 */
175 enum Communication { NoCommunication = 0, Stdin = 1, Stdout = 2, Stderr = 4,
176 AllOutput = 6, All = 7,
177 NoRead };
178
179 /**
180 * Run-modes for a child process.
181 */
182 enum RunMode {
183 /**
184 * The application does not receive notifications from the subprocess when
185 * it is finished or aborted.
186 */
187 DontCare,
188 /**
189 * The application is notified when the subprocess dies.
190 */
191 NotifyOnExit,
192 /**
193 * The application is suspended until the started process is finished.
194 */
195 Block };
196
197 /**
198 * Constructor
199 */
200 OProcess( QObject *parent = 0, const char *name = 0 );
201 /**
202 * Constructor
203 */
204 OProcess( const QString &arg0, QObject *parent = 0, const char *name = 0 );
205 /**
206 * Constructor
207 */
208 OProcess( const QStringList &args, QObject *parent = 0, const char *name = 0 );
209
210 /**
211 *Destructor:
212 *
213 * If the process is running when the destructor for this class
214 * is called, the child process is killed with a SIGKILL, but
215 * only if the run mode is not of type @p DontCare.
216 * Processes started as @p DontCare keep running anyway.
217 */
218 virtual ~OProcess();
219
220 /**
221 @deprecated
222
223 The use of this function is now deprecated. -- Please use the
224 "operator<<" instead of "setExecutable".
225
226 Sets the executable to be started with this OProcess object.
227 Returns false if the process is currently running (in that
228 case the executable remains unchanged.)
229
230 @see operator<<
231
232 */
233 bool setExecutable( const QString& proc );
234
235
236 /**
237 * Sets the executable and the command line argument list for this process.
238 *
239 * For example, doing an "ls -l /usr/local/bin" can be achieved by:
240 * <pre>
241 * OProcess p;
242 * ...
243 * p << "ls" << "-l" << "/usr/local/bin"
244 * </pre>
245 *
246 **/
247 OProcess &operator<<( const QString& arg );
248 /**
249 * Similar to previous method, takes a char *, supposed to be in locale 8 bit already.
250 */
251 OProcess &operator<<( const char * arg );
252 /**
253 * Similar to previous method, takes a QCString, supposed to be in locale 8 bit already.
254 */
255 OProcess &operator<<( const QCString & arg );
256
257 /**
258 * Sets the executable and the command line argument list for this process,
259 * in a single method call, or add a list of arguments.
260 **/
261 OProcess &operator<<( const QStringList& args );
262
263 /**
264 * Clear a command line argument list that has been set by using
265 * the "operator<<".
266 */
267 void clearArguments();
268
269 /**
270 * Starts the process.
271 * For a detailed description of the
272 * various run modes and communication semantics, have a look at the
273 * general description of the OProcess class.
274 *
275 * The following problems could cause this function to
276 * return false:
277 *
278 * @li The process is already running.
279 * @li The command line argument list is empty.
280 * @li The starting of the process failed (could not fork).
281 * @li The executable was not found.
282 *
283 * @param comm Specifies which communication links should be
284 * established to the child process (stdin/stdout/stderr). By default,
285 * no communication takes place and the respective communication
286 * signals will never get emitted.
287 *
288 * @return true on success, false on error
289 * (see above for error conditions)
290 **/
291 virtual bool start( RunMode runmode = NotifyOnExit,
292 Communication comm = NoCommunication );
293
294 /**
295 * Stop the process (by sending it a signal).
296 *
297 * @param signoThe signal to send. The default is SIGTERM.
298 * @return @p true if the signal was delivered successfully.
299 */
300 virtual bool kill( int signo = SIGTERM );
301
302 /**
303 @return @p true if the process is (still) considered to be running
304 */
305 bool isRunning() const;
306
307 /** Returns the process id of the process.
308 *
309 * If it is called after
310 * the process has exited, it returns the process id of the last
311 * child process that was created by this instance of OProcess.
312 *
313 * Calling it before any child process has been started by this
314 * OProcess instance causes pid() to return 0.
315 **/
316 pid_t pid() const;
317
318 /**
319 * Suspend processing of data from stdout of the child process.
320 */
321 void suspend();
322
323 /**
324 * Resume processing of data from stdout of the child process.
325 */
326 void resume();
327
328 /**
329 * @return @p true if the process has already finished and has exited
330 * "voluntarily", ie: it has not been killed by a signal.
331 *
332 * Note that you should check @ref OProcess::exitStatus() to determine
333 * whether the process completed its task successful or not.
334 */
335 bool normalExit() const;
336
337 /**
338 * Returns the exit status of the process.
339 *
340 * Please use
341 * @ref OProcess::normalExit() to check whether the process has exited
342 * cleanly (i.e., @ref OProcess::normalExit() returns @p true) before calling
343 * this function because if the process did not exit normally,
344 * it does not have a valid exit status.
345 */
346 int exitStatus() const;
347
348
349 /**
350 * Transmit data to the child process's stdin.
351 *
352 * OProcess::writeStdin may return false in the following cases:
353 *
354 * @li The process is not currently running.
355 *
356 * @li Communication to stdin has not been requested in the @ref start() call.
357 *
358 * @li Transmission of data to the child process by a previous call to
359 * @ref writeStdin() is still in progress.
360 *
361 * Please note that the data is sent to the client asynchronously,
362 * so when this function returns, the data might not have been
363 * processed by the child process.
364 *
365 * If all the data has been sent to the client, the signal
366 * @ref wroteStdin() will be emitted.
367 *
368 * Please note that you must not free "buffer" or call @ref writeStdin()
369 * again until either a @ref wroteStdin() signal indicates that the
370 * data has been sent or a @ref processHasExited() signal shows that
371 * the child process is no longer alive...
372 **/
373 bool writeStdin( const char *buffer, int buflen );
374
375 void flushStdin();
376
377 /**
378 * This causes the stdin file descriptor of the child process to be
379 * closed indicating an "EOF" to the child.
380 *
381 * @return @p false if no communication to the process's stdin
382 * had been specified in the call to @ref start().
383 */
384 bool closeStdin();
385
386 /**
387 * This causes the stdout file descriptor of the child process to be
388 * closed.
389 *
390 * @return @p false if no communication to the process's stdout
391 * had been specified in the call to @ref start().
392 */
393 bool closeStdout();
394
395 /**
396 * This causes the stderr file descriptor of the child process to be
397 * closed.
398 *
399 * @return @p false if no communication to the process's stderr
400 * had been specified in the call to @ref start().
401 */
402 bool closeStderr();
403
404 /**
405 * Lets you see what your arguments are for debugging.
406 * \todo make const
407 */
408
409 const QValueList<QCString> &args()
410 {
411 return arguments;
412 }
413
414 /**
415 * Controls whether the started process should drop any
416 * setuid/segid privileges or whether it should keep them
417 *
418 * The default is @p false : drop privileges
419 */
420 void setRunPrivileged( bool keepPrivileges );
421
422 /**
423 * Returns whether the started process will drop any
424 * setuid/segid privileges or whether it will keep them
425 */
426 bool runPrivileged() const;
427
428 /**
429 * Modifies the environment of the process to be started.
430 * This function must be called before starting the process.
431 */
432 void setEnvironment( const QString &name, const QString &value );
433
434 /**
435 * Changes the current working directory (CWD) of the process
436 * to be started.
437 * This function must be called before starting the process.
438 */
439 void setWorkingDirectory( const QString &dir );
440
441 /**
442 * Specify whether to start the command via a shell or directly.
443 * The default is to start the command directly.
444 * If @p useShell is true @p shell will be used as shell, or
445 * if shell is empty, the standard shell is used.
446 * @p quote A flag indicating whether to quote the arguments.
447 *
448 * When using a shell, the caller should make sure that all filenames etc.
449 * are properly quoted when passed as argument.
450 * @see quote()
451 */
452 void setUseShell( bool useShell, const char *shell = 0 );
453
454 /**
455 * This function can be used to quote an argument string such that
456 * the shell processes it properly. This is e. g. necessary for
457 * user-provided file names which may contain spaces or quotes.
458 * It also prevents expansion of wild cards and environment variables.
459 */
460 static QString quote( const QString &arg );
461
462 /**
463 * Detaches OProcess from child process. All communication is closed.
464 * No exit notification is emitted any more for the child process.
465 * Deleting the OProcess will no longer kill the child process.
466 * Note that the current process remains the parent process of the
467 * child process.
468 */
469 void detach();
470
471 /**
472 * @return the PID of @a process, or -1 if the process is not running
473 */
474 static int processPID( const QString& process );
475
476signals:
477
478 /**
479 * Emitted after the process has terminated when
480 * the process was run in the @p NotifyOnExit (==default option to
481 * @ref start()) or the @ref Block mode.
482 **/
483 void processExited( Opie::Core::OProcess *proc );
484
485
486 /**
487 * Emitted, when output from the child process has
488 * been received on stdout.
489 *
490 * To actually get
491 * these signals, the respective communication link (stdout/stderr)
492 * has to be turned on in @ref start().
493 *
494 * @param buffer The data received.
495 * @param buflen The number of bytes that are available.
496 *
497 * You should copy the information contained in @p buffer to your private
498 * data structures before returning from this slot.
499 **/
500 void receivedStdout( Opie::Core::OProcess *proc, char *buffer, int buflen );
501
502 /**
503 * Emitted when output from the child process has
504 * been received on stdout.
505 *
506 * To actually get these signals, the respective communications link
507 * (stdout/stderr) has to be turned on in @ref start() and the
508 * @p NoRead flag should have been passed.
509 *
510 * You will need to explicitly call resume() after your call to start()
511 * to begin processing data from the child process's stdout. This is
512 * to ensure that this signal is not emitted when no one is connected
513 * to it, otherwise this signal will not be emitted.
514 *
515 * The data still has to be read from file descriptor @p fd.
516 **/
517 void receivedStdout( int fd, int &len );
518
519
520 /**
521 * Emitted, when output from the child process has
522 * been received on stderr.
523 * To actually get
524 * these signals, the respective communication link (stdout/stderr)
525 * has to be turned on in @ref start().
526 *
527 * @param buffer The data received.
528 * @param buflen The number of bytes that are available.
529 *
530 * You should copy the information contained in @p buffer to your private
531 * data structures before returning from this slot.
532 */
533 void receivedStderr( Opie::Core::OProcess *proc, char *buffer, int buflen );
534
535 /**
536 * Emitted after all the data that has been
537 * specified by a prior call to @ref writeStdin() has actually been
538 * written to the child process.
539 **/
540 void wroteStdin( Opie::Core::OProcess *proc );
541
542protected slots:
543
544 /**
545 * This slot gets activated when data from the child's stdout arrives.
546 * It usually calls "childOutput"
547 */
548 void slotChildOutput( int fdno );
549
550 /**
551 * This slot gets activated when data from the child's stderr arrives.
552 * It usually calls "childError"
553 */
554 void slotChildError( int fdno );
555 /*
556 Slot functions for capturing stdout and stderr of the child
557 */
558
559 /**
560 * Called when another bulk of data can be sent to the child's
561 * stdin. If there is no more data to be sent to stdin currently
562 * available, this function must disable the QSocketNotifier "innot".
563 */
564 void slotSendData( int dummy );
565
566protected:
567
568 /**
569 * Sets up the environment according to the data passed via
570 * setEnvironment(...)
571 */
572 void setupEnvironment();
573
574 /**
575 * The list of the process' command line arguments. The first entry
576 * in this list is the executable itself.
577 */
578 QValueList<QCString> arguments;
579 /**
580 * How to run the process (Block, NotifyOnExit, DontCare). You should
581 * not modify this data member directly from derived classes.
582 */
583 RunMode run_mode;
584 /**
585 * true if the process is currently running. You should not
586 * modify this data member directly from derived classes. For
587 * reading the value of this data member, please use "isRunning()"
588 * since "runs" will probably be made private in later versions
589 * of OProcess.
590 */
591 bool runs;
592
593 /**
594 * The PID of the currently running process (see "getPid()").
595 * You should not modify this data member in derived classes.
596 * Please use "getPid()" instead of directly accessing this
597 * member function since it will probably be made private in
598 * later versions of OProcess.
599 */
600 pid_t pid_;
601
602 /**
603 * The process' exit status as returned by "waitpid". You should not
604 * modify the value of this data member from derived classes. You should
605 * rather use @ref exitStatus than accessing this data member directly
606 * since it will probably be made private in further versions of
607 * OProcess.
608 */
609 int status;
610
611
612 /**
613 * See setRunPrivileged()
614 */
615 bool keepPrivs;
616
617 /*
618 Functions for setting up the sockets for communication.
619 setupCommunication
620 -- is called from "start" before "fork"ing.
621 commSetupDoneP
622 -- completes communication socket setup in the parent
623 commSetupDoneC
624 -- completes communication setup in the child process
625 commClose
626 -- frees all allocated communication resources in the parent
627 after the process has exited
628 */
629
630 /**
631 * This function is called from "OProcess::start" right before a "fork" takes
632 * place. According to
633 * the "comm" parameter this function has to initialize the "in", "out" and
634 * "err" data member of OProcess.
635 *
636 * This function should return 0 if setting the needed communication channels
637 * was successful.
638 *
639 * The default implementation is to create UNIX STREAM sockets for the communication,
640 * but you could overload this function and establish a TCP/IP communication for
641 * network communication, for example.
642 */
643 virtual int setupCommunication( Communication comm );
644
645 /**
646 * Called right after a (successful) fork on the parent side. This function
647 * will usually do some communications cleanup, like closing the reading end
648 * of the "stdin" communication channel.
649 *
650 * Furthermore, it must also create the QSocketNotifiers "innot", "outnot" and
651 * "errnot" and connect their Qt slots to the respective OProcess member functions.
652 *
653 * For a more detailed explanation, it is best to have a look at the default
654 * implementation of "setupCommunication" in kprocess.cpp.
655 */
656 virtual int commSetupDoneP();
657
658 /**
659 * Called right after a (successful) fork, but before an "exec" on the child
660 * process' side. It usually just closes the unused communication ends of
661 * "in", "out" and "err" (like the writing end of the "in" communication
662 * channel.
663 */
664 virtual int commSetupDoneC();
665
666
667 /**
668 * Immediately called after a process has exited. This function normally
669 * calls commClose to close all open communication channels to this
670 * process and emits the "processExited" signal (if the process was
671 * not running in the "DontCare" mode).
672 */
673 virtual void processHasExited( int state );
674
675 /**
676 * Should clean up the communication links to the child after it has
677 * exited. Should be called from "processHasExited".
678 */
679 virtual void commClose();
680
681
682 /**
683 * the socket descriptors for stdin/stdout/stderr.
684 */
685 int out[ 2 ];
686 int in[ 2 ];
687 int err[ 2 ];
688
689 /**
690 * The socket notifiers for the above socket descriptors.
691 */
692 QSocketNotifier *innot;
693 QSocketNotifier *outnot;
694 QSocketNotifier *errnot;
695
696 /**
697 * Lists the communication links that are activated for the child
698 * process. Should not be modified from derived classes.
699 */
700 Communication communication;
701
702 /**
703 * Called by "slotChildOutput" this function copies data arriving from the
704 * child process's stdout to the respective buffer and emits the signal
705 * "@ref receivedStderr".
706 */
707 int childOutput( int fdno );
708
709 /**
710 * Called by "slotChildOutput" this function copies data arriving from the
711 * child process's stdout to the respective buffer and emits the signal
712 * "@ref receivedStderr"
713 */
714 int childError( int fdno );
715
716 // information about the data that has to be sent to the child:
717
718 const char *input_data; // the buffer holding the data
719 int input_sent; // # of bytes already transmitted
720 int input_total; // total length of input_data
721
722 /**
723 * @ref OProcessController is a friend of OProcess because it has to have
724 * access to various data members.
725 */
726 friend class Internal::OProcessController;
727
728private:
729 /**
730 * Searches for a valid shell.
731 * Here is the algorithm used for finding an executable shell:
732 *
733 * @li Try the executable pointed to by the "SHELL" environment
734 * variable with white spaces stripped off
735 *
736 * @li If your process runs with uid != euid or gid != egid, a shell
737 * not listed in /etc/shells will not used.
738 *
739 * @li If no valid shell could be found, "/bin/sh" is used as a last resort.
740 */
741 QCString searchShell();
742
743 /**
744 * Used by @ref searchShell in order to find out whether the shell found
745 * is actually executable at all.
746 */
747 bool isExecutable( const QCString &filename );
748
749 // Disallow assignment and copy-construction
750 OProcess( const OProcess& );
751 OProcess& operator= ( const OProcess& );
752
753private:
754 void init ( );
755 Internal::OProcessPrivate *d;
756};
757}
758}
759
760#endif
761