summaryrefslogtreecommitdiffstats
path: root/tdecore/kprocess.cpp
blob: 85e7620a480c8f81137e4d09bb85f48c35c39332 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
/*

   $Id$

   This file is part of the KDE libraries
   Copyright (C) 1997 Christian Czezatke ([email protected])

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/


#include "kprocess.h"
#include "kprocctrl.h"
#include "kpty.h"

#include <config.h>

#ifdef __sgi
#define __svr4__
#endif

#ifdef __osf__
#define _OSF_SOURCE
#include <float.h>
#endif

#ifdef _AIX
#define _ALL_SOURCE
#endif

#ifdef Q_OS_UNIX
#include <sys/socket.h>
#include <sys/ioctl.h>
#endif

#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/wait.h>

#ifdef HAVE_SYS_STROPTS_H
#include <sys/stropts.h>	// Defines I_PUSH
#define _NEW_TTY_CTRL
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#include <errno.h>
#include <assert.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>

#include <tqfile.h>
#include <tqsocketnotifier.h>
#include <tqapplication.h>

#include <kdebug.h>
#include <kstandarddirs.h>
#include <kuser.h>


//////////////////
// private data //
//////////////////

class TDEProcessPrivate {
public:
   TDEProcessPrivate() : 
     usePty(TDEProcess::NoCommunication),
     addUtmp(false), useShell(false),
#ifdef Q_OS_UNIX
     pty(0),
#endif
     priority(0)
   {
   }

   TDEProcess::Communication usePty;
   bool addUtmp : 1;
   bool useShell : 1;

#ifdef Q_OS_UNIX
   KPty *pty;
#endif

   int priority;

   TQMap<TQString,TQString> env;
   TQString wd;
   TQCString shell;
   TQCString executable;
};

/////////////////////////////
// public member functions //
/////////////////////////////

TDEProcess::TDEProcess( TQObject* parent, const char *name )
  : TQObject( parent, name ),
    run_mode(NotifyOnExit),
    runs(false),
    pid_(0),
    status(0),
    keepPrivs(false),
    innot(0),
    outnot(0),
    errnot(0),
    communication(NoCommunication),
    input_data(0),
    input_sent(0),
    input_total(0)
{
  TDEProcessController::ref();
  TDEProcessController::theTDEProcessController->addTDEProcess(this);

  d = new TDEProcessPrivate;

  out[0] = out[1] = -1;
  in[0] = in[1] = -1;
  err[0] = err[1] = -1;
}

TDEProcess::TDEProcess()
  : TQObject(),
    run_mode(NotifyOnExit),
    runs(false),
    pid_(0),
    status(0),
    keepPrivs(false),
    innot(0),
    outnot(0),
    errnot(0),
    communication(NoCommunication),
    input_data(0),
    input_sent(0),
    input_total(0)
{
  TDEProcessController::ref();
  TDEProcessController::theTDEProcessController->addTDEProcess(this);

  d = new TDEProcessPrivate;

  out[0] = out[1] = -1;
  in[0] = in[1] = -1;
  err[0] = err[1] = -1;
}

void
TDEProcess::setEnvironment(const TQString &name, const TQString &value)
{
   d->env.insert(name, value);
}

void
TDEProcess::setWorkingDirectory(const TQString &dir)
{
   d->wd = dir;   
} 

void 
TDEProcess::setupEnvironment()
{
   TQMap<TQString,TQString>::Iterator it;
   for(it = d->env.begin(); it != d->env.end(); ++it)
   {
      setenv(TQFile::encodeName(it.key()).data(),
             TQFile::encodeName(it.data()).data(), 1);
   }
   if (!d->wd.isEmpty())
   {
      chdir(TQFile::encodeName(d->wd).data());
   }
}

void
TDEProcess::setRunPrivileged(bool keepPrivileges)
{
   keepPrivs = keepPrivileges;
}

bool
TDEProcess::runPrivileged() const
{
   return keepPrivs;
}

bool
TDEProcess::setPriority(int prio)
{
#ifdef Q_OS_UNIX
    if (runs) {
        if (setpriority(PRIO_PROCESS, pid_, prio))
            return false;
    } else {
        if (prio > 19 || prio < (geteuid() ? getpriority(PRIO_PROCESS, 0) : -20))
            return false;
    }
#endif
    d->priority = prio;
    return true;
}

TDEProcess::~TDEProcess()
{
  if (run_mode != DontCare)
    kill(SIGKILL);
  detach();

#ifdef Q_OS_UNIX
  delete d->pty;
#endif
  delete d;

  TDEProcessController::theTDEProcessController->removeTDEProcess(this);
  TDEProcessController::deref();
}

void TDEProcess::detach()
{
  if (runs) {
    TDEProcessController::theTDEProcessController->addProcess(pid_);
    runs = false;
    pid_ = 0; // close without draining
    commClose(); // Clean up open fd's and socket notifiers.
  }
}

void TDEProcess::setBinaryExecutable(const char *filename)
{
   d->executable = filename;
}

bool TDEProcess::setExecutable(const TQString& proc)
{
  if (runs) return false;

  if (proc.isEmpty())  return false;

  if (!arguments.isEmpty())
     arguments.remove(arguments.begin());
  arguments.prepend(TQFile::encodeName(proc));

  return true;
}

TDEProcess &TDEProcess::operator<<(const TQStringList& args)
{
  TQStringList::ConstIterator it = args.begin();
  for ( ; it != args.end() ; ++it )
      arguments.append(TQFile::encodeName(*it));
  return *this;
}

TDEProcess &TDEProcess::operator<<(const TQCString& arg)
{
  return operator<< (arg.data());
}

TDEProcess &TDEProcess::operator<<(const char* arg)
{
  arguments.append(arg);
  return *this;
}

TDEProcess &TDEProcess::operator<<(const TQString& arg)
{
  arguments.append(TQFile::encodeName(arg));
  return *this;
}

void TDEProcess::clearArguments()
{
  arguments.clear();
}

bool TDEProcess::start(RunMode runmode, Communication comm)
{
  if (runs) {
    kdDebug(175) << "Attempted to start an already running process" << endl;
    return false;
  }

  uint n = arguments.count();
  if (n == 0) {
    kdDebug(175) << "Attempted to start a process without arguments" << endl;
    return false;
  }
#ifdef Q_OS_UNIX
  char **arglist;
  TQCString shellCmd;
  if (d->useShell)
  {
      if (d->shell.isEmpty()) {
        kdDebug(175) << "Invalid shell specified" << endl;
        return false;
      }

      for (uint i = 0; i < n; i++) {
          shellCmd += arguments[i];
          shellCmd += " "; // CC: to separate the arguments
      }

      arglist = static_cast<char **>(malloc( 4 * sizeof(char *)));
      arglist[0] = d->shell.data();
      arglist[1] = (char *) "-c";
      arglist[2] = shellCmd.data();
      arglist[3] = 0;
  }
  else
  {
      arglist = static_cast<char **>(malloc( (n + 1) * sizeof(char *)));
      for (uint i = 0; i < n; i++)
         arglist[i] = arguments[i].data();
      arglist[n] = 0;
  }

  run_mode = runmode;

  if (!setupCommunication(comm))
  {
      kdDebug(175) << "Could not setup Communication!" << endl;
      free(arglist);
      return false;
  }

  // We do this in the parent because if we do it in the child process
  // gdb gets confused when the application runs from gdb.
#ifdef HAVE_INITGROUPS
  struct passwd *pw = geteuid() ? 0 : getpwuid(getuid());
#endif

  int fd[2];
  if (pipe(fd))
     fd[0] = fd[1] = -1; // Pipe failed.. continue

  // we don't use vfork() because
  // - it has unclear semantics and is not standardized
  // - we do way too much magic in the child
  pid_ = fork();
  if (pid_ == 0) {
        // The child process

        close(fd[0]);
        // Closing of fd[1] indicates that the execvp() succeeded!
        fcntl(fd[1], F_SETFD, FD_CLOEXEC);

        if (!commSetupDoneC())
          kdDebug(175) << "Could not finish comm setup in child!" << endl;

        // reset all signal handlers
        struct sigaction act;
        sigemptyset(&act.sa_mask);
        act.sa_handler = SIG_DFL;
        act.sa_flags = 0;
        for (int sig = 1; sig < NSIG; sig++)
          sigaction(sig, &act, 0L);

        if (d->priority)
            setpriority(PRIO_PROCESS, 0, d->priority);

        if (!runPrivileged())
        {
           setgid(getgid());
#ifdef HAVE_INITGROUPS
           if (pw)
              initgroups(pw->pw_name, pw->pw_gid);
#endif
	   if (geteuid() != getuid())
	       setuid(getuid());
	   if (geteuid() != getuid())
	       _exit(1);
        }

        setupEnvironment();

        if (runmode == DontCare || runmode == OwnGroup)
          setsid();

        const char *executable = arglist[0];
        if (!d->executable.isEmpty())
           executable = d->executable.data();
        execvp(executable, arglist);

        char resultByte = 1;
        write(fd[1], &resultByte, 1);
        _exit(-1);
  } else if (pid_ == -1) {
        // forking failed

        // commAbort();
        pid_ = 0;
        free(arglist);
        return false;
  }
  // the parent continues here
  free(arglist);

  if (!commSetupDoneP())
    kdDebug(175) << "Could not finish comm setup in parent!" << endl;

  // Check whether client could be started.
  close(fd[1]);
  for(;;)
  {
     char resultByte;
     int n = ::read(fd[0], &resultByte, 1);
     if (n == 1)
     {
         // exec() failed
         close(fd[0]);
         waitpid(pid_, 0, 0);
         pid_ = 0;
         commClose();
         return false;
     }
     if (n == -1)
     {
        if (errno == EINTR)
           continue; // Ignore
     }
     break; // success
  }
  close(fd[0]);

  runs = true;
  switch (runmode)
  {
  case Block:
    for (;;)
    {
      commClose(); // drain only, unless obsolete reimplementation
      if (!runs)
      {
        // commClose detected data on the process exit notifification pipe
        TDEProcessController::theTDEProcessController->unscheduleCheck();
        if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too
        {
          commClose(); // this time for real (runs is false)
          TDEProcessController::theTDEProcessController->rescheduleCheck();
          break;
        }
        runs = true; // for next commClose() iteration
      }
      else
      {
        // commClose is an obsolete reimplementation and waited until
        // all output channels were closed (or it was interrupted).
        // there is a chance that it never gets here ...
        waitpid(pid_, &status, 0);
        runs = false;
        break;
      }
    }
    // why do we do this? i think this signal should be emitted _only_
    // after the process has successfully run _asynchronously_ --ossi
    emit processExited(this);
    break;
  default: // NotifyOnExit & OwnGroup
    input_data = 0; // Discard any data for stdin that might still be there
    break;
  }
  return true;
#else
  //TODO
  return false;
#endif
}



bool TDEProcess::kill(int signo)
{
#ifdef Q_OS_UNIX
  if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo))
    return true;
#endif
  return false;
}



bool TDEProcess::isRunning() const
{
  return runs;
}



pid_t TDEProcess::pid() const
{
  return pid_;
}

#ifndef timersub
# define timersub(a, b, result) \
  do { \
    (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
    (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
    if ((result)->tv_usec < 0) { \
      --(result)->tv_sec; \
      (result)->tv_usec += 1000000; \
    } \
  } while (0)
#endif

bool TDEProcess::wait(int timeout)
{
  if (!runs)
    return true;

#ifndef __linux__
  struct timeval etv;
#endif
  struct timeval tv, *tvp;
  if (timeout < 0)
    tvp = 0;
  else
  {
#ifndef __linux__
    gettimeofday(&etv, 0);
    etv.tv_sec += timeout;
#else
    tv.tv_sec = timeout;
    tv.tv_usec = 0;
#endif
    tvp = &tv;
  }

#ifdef Q_OS_UNIX
  int fd = TDEProcessController::theTDEProcessController->notifierFd();
  for(;;)
  {
    fd_set fds;
    FD_ZERO( &fds );
    FD_SET( fd, &fds );

#ifndef __linux__
    if (tvp)
    {
      gettimeofday(&tv, 0);
      timersub(&etv, &tv, &tv);
      if (tv.tv_sec < 0)
        tv.tv_sec = tv.tv_usec = 0;
    }
#endif

    switch( select( fd+1, &fds, 0, 0, tvp ) )
    {
    case -1:
      if( errno == EINTR )
        break;
      // fall through; should happen if tvp->tv_sec < 0
    case 0:
      TDEProcessController::theTDEProcessController->rescheduleCheck();
      return false;
    default:
      TDEProcessController::theTDEProcessController->unscheduleCheck();
      if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too
      {
        processHasExited(status);
        TDEProcessController::theTDEProcessController->rescheduleCheck();
        return true;
      }
    }
  }
#endif //Q_OS_UNIX
  return false;
}



bool TDEProcess::normalExit() const
{
  return (pid_ != 0) && !runs && WIFEXITED(status);
}


bool TDEProcess::signalled() const
{
  return (pid_ != 0) && !runs && WIFSIGNALED(status);
}


bool TDEProcess::coreDumped() const
{
#ifdef WCOREDUMP
  return signalled() && WCOREDUMP(status);
#else
  return false;
#endif
}


int TDEProcess::exitStatus() const
{
  return WEXITSTATUS(status);
}


int TDEProcess::exitSignal() const
{
  return WTERMSIG(status);
}


bool TDEProcess::writeStdin(const char *buffer, int buflen)
{
  // if there is still data pending, writing new data
  // to stdout is not allowed (since it could also confuse
  // kprocess ...)
  if (input_data != 0)
    return false;

  if (communication & Stdin) {
    input_data = buffer;
    input_sent = 0;
    input_total = buflen;
    innot->setEnabled(true);
    if (input_total)
       slotSendData(0);
    return true;
  } else
    return false;
}

void TDEProcess::suspend()
{
  if (outnot)
     outnot->setEnabled(false);
}

void TDEProcess::resume()
{
  if (outnot)
     outnot->setEnabled(true);
}

bool TDEProcess::closeStdin()
{
  if (communication & Stdin) {
    communication = (Communication) (communication & ~Stdin);
    delete innot;
    innot = 0;
    if (!(d->usePty & Stdin))
      close(in[1]);
    in[1] = -1;
    return true;
  } else
    return false;
}

bool TDEProcess::closeStdout()
{
  if (communication & Stdout) {
    communication = (Communication) (communication & ~Stdout);
    delete outnot;
    outnot = 0;
    if (!(d->usePty & Stdout))
      close(out[0]);
    out[0] = -1;
    return true;
  } else
    return false;
}

bool TDEProcess::closeStderr()
{
  if (communication & Stderr) {
    communication = (Communication) (communication & ~Stderr);
    delete errnot;
    errnot = 0;
    if (!(d->usePty & Stderr))
      close(err[0]);
    err[0] = -1;
    return true;
  } else
    return false;
}

bool TDEProcess::closePty()
{
#ifdef Q_OS_UNIX
  if (d->pty && d->pty->masterFd() >= 0) {
    if (d->addUtmp)
      d->pty->logout();
    d->pty->close();
    return true;
  } else
    return false;
#else
    return false;
#endif
}

void TDEProcess::closeAll()
{
  closeStdin();
  closeStdout();
  closeStderr();
  closePty();
}

/////////////////////////////
// protected slots         //
/////////////////////////////



void TDEProcess::slotChildOutput(int fdno)
{
  if (!childOutput(fdno))
     closeStdout();
}


void TDEProcess::slotChildError(int fdno)
{
  if (!childError(fdno))
     closeStderr();
}


void TDEProcess::slotSendData(int)
{
  if (input_sent == input_total) {
    innot->setEnabled(false);
    input_data = 0;
    emit wroteStdin(this);
  } else {
    int result = ::write(in[1], input_data+input_sent, input_total-input_sent);
    if (result >= 0)
    {
       input_sent += result;
    }
    else if ((errno != EAGAIN) && (errno != EINTR))
    {
       kdDebug(175) << "Error writing to stdin of child process" << endl;
       closeStdin();
    }
  }
}

void TDEProcess::setUseShell(bool useShell, const char *shell)
{
  d->useShell = useShell;
  if (shell && *shell)
    d->shell = shell;
  else
// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh
#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__GNU__) && !defined(__DragonFly__)
  // Solaris POSIX ...
  if (!access( "/usr/xpg4/bin/sh", X_OK ))
    d->shell = "/usr/xpg4/bin/sh";
  else
  // ... which links here anyway
  if (!access( "/bin/ksh", X_OK ))
    d->shell = "/bin/ksh";
  else
  // dunno, maybe superfluous?
  if (!access( "/usr/ucb/sh", X_OK ))
    d->shell = "/usr/ucb/sh";
  else
#endif
    d->shell = "/bin/sh";
}

#ifdef Q_OS_UNIX
void TDEProcess::setUsePty(Communication usePty, bool addUtmp)
{
  d->usePty = usePty;
  d->addUtmp = addUtmp;
  if (usePty) {
    if (!d->pty)
      d->pty = new KPty;
  } else {
    delete d->pty;
    d->pty = 0;
  }
}

KPty *TDEProcess::pty() const
{
  return d->pty;
}
#endif //Q_OS_UNIX

TQString TDEProcess::quote(const TQString &arg)
{
    TQChar q('\'');
    return TQString(arg).replace(q, "'\\''").prepend(q).append(q);
}


//////////////////////////////
// private member functions //
//////////////////////////////


void TDEProcess::processHasExited(int state)
{
    // only successfully run NotifyOnExit processes ever get here

    status = state;
    runs = false; // do this before commClose, so it knows we're dead

    commClose(); // cleanup communication sockets

    if (run_mode != DontCare)
      emit processExited(this);
}



int TDEProcess::childOutput(int fdno)
{
  if (communication & NoRead) {
     int len = -1;
     emit receivedStdout(fdno, len);
     errno = 0; // Make sure errno doesn't read "EAGAIN"
     return len;
  }
  else
  {
     char buffer[1025];
     int len;

     len = ::read(fdno, buffer, 1024);
     
     if (len > 0) {
        buffer[len] = 0; // Just in case.
        emit receivedStdout(this, buffer, len);
     }
     return len;
  }
}

int TDEProcess::childError(int fdno)
{
  char buffer[1025];
  int len;

  len = ::read(fdno, buffer, 1024);

  if (len > 0) {
     buffer[len] = 0; // Just in case.
     emit receivedStderr(this, buffer, len);
  }
  return len;
}


int TDEProcess::setupCommunication(Communication comm)
{
#ifdef Q_OS_UNIX
  // PTY stuff //
  if (d->usePty)
  {
    // cannot communicate on both stderr and stdout if they are both on the pty
    if (!(~(comm & d->usePty) & (Stdout | Stderr))) {
       kdWarning(175) << "Invalid usePty/communication combination (" << d->usePty << "/" << comm << ")" << endl;
       return 0;
    }
    if (!d->pty->open())
       return 0;

    int rcomm = comm & d->usePty;
    int mfd = d->pty->masterFd();
    if (rcomm & Stdin)
      in[1] = mfd;
    if (rcomm & Stdout)
      out[0] = mfd;
    if (rcomm & Stderr)
      err[0] = mfd;
  }

  communication = comm;

  comm = (Communication) (comm & ~d->usePty);
  if (comm & Stdin) {
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, in))
      goto fail0;
    fcntl(in[0], F_SETFD, FD_CLOEXEC);
    fcntl(in[1], F_SETFD, FD_CLOEXEC);
  }
  if (comm & Stdout) {
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, out))
      goto fail1;
    fcntl(out[0], F_SETFD, FD_CLOEXEC);
    fcntl(out[1], F_SETFD, FD_CLOEXEC);
  }
  if (comm & Stderr) {
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, err))
      goto fail2;
    fcntl(err[0], F_SETFD, FD_CLOEXEC);
    fcntl(err[1], F_SETFD, FD_CLOEXEC);
  }
  return 1; // Ok
 fail2:
  if (comm & Stdout)
  {
    close(out[0]);
    close(out[1]);
    out[0] = out[1] = -1;
  }
 fail1:
  if (comm & Stdin)
  {
    close(in[0]);
    close(in[1]);
    in[0] = in[1] = -1;
  }
 fail0:
  communication = NoCommunication;
#endif //Q_OS_UNIX
  return 0; // Error
}



int TDEProcess::commSetupDoneP()
{
  int rcomm = communication & ~d->usePty;
  if (rcomm & Stdin)
    close(in[0]);
  if (rcomm & Stdout)
    close(out[1]);
  if (rcomm & Stderr)
    close(err[1]);
  in[0] = out[1] = err[1] = -1;

  // Don't create socket notifiers if no interactive comm is to be expected
  if (run_mode != NotifyOnExit && run_mode != OwnGroup)
    return 1;

  if (communication & Stdin) {
    fcntl(in[1], F_SETFL, O_NONBLOCK | fcntl(in[1], F_GETFL));
    innot =  new TQSocketNotifier(in[1], TQSocketNotifier::Write, this);
    TQ_CHECK_PTR(innot);
    innot->setEnabled(false); // will be enabled when data has to be sent
    TQObject::connect(innot, TQ_SIGNAL(activated(int)),
                     this, TQ_SLOT(slotSendData(int)));
  }

  if (communication & Stdout) {
    outnot = new TQSocketNotifier(out[0], TQSocketNotifier::Read, this);
    TQ_CHECK_PTR(outnot);
    TQObject::connect(outnot, TQ_SIGNAL(activated(int)),
                     this, TQ_SLOT(slotChildOutput(int)));
    if (communication & NoRead)
        suspend();
  }

  if (communication & Stderr) {
    errnot = new TQSocketNotifier(err[0], TQSocketNotifier::Read, this );
    TQ_CHECK_PTR(errnot);
    TQObject::connect(errnot, TQ_SIGNAL(activated(int)),
                     this, TQ_SLOT(slotChildError(int)));
  }

  return 1;
}



int TDEProcess::commSetupDoneC()
{
  int ok = 1;
#ifdef Q_OS_UNIX

  if (d->usePty & Stdin) {
    if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) ok = 0;
  } else if (communication & Stdin) {
    if (dup2(in[0], STDIN_FILENO) < 0) ok = 0;
  } else {
    int null_fd = open( "/dev/null", O_RDONLY );
    if (dup2( null_fd, STDIN_FILENO ) < 0) ok = 0;
    close( null_fd );
  }
  struct linger so;
  memset(&so, 0, sizeof(so));
  if (d->usePty & Stdout) {
    if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) ok = 0;
  } else if (communication & Stdout) {
    if (dup2(out[1], STDOUT_FILENO) < 0 ||
        setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so)))
      ok = 0;
    if (communication & MergedStderr) {
      if (dup2(out[1], STDERR_FILENO) < 0)
        ok = 0;
    }
  }
  if (d->usePty & Stderr) {
    if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) ok = 0;
  } else if (communication & Stderr) {
    if (dup2(err[1], STDERR_FILENO) < 0 ||
        setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so)))
      ok = 0;
  }

  // don't even think about closing all open fds here or anywhere else

  // PTY stuff //
  if (d->usePty) {
    d->pty->setCTty();
    if (d->addUtmp)
      d->pty->login(KUser(KUser::UseRealUserID).loginName().local8Bit().data(), getenv("DISPLAY"));
  }
#endif //Q_OS_UNIX

  return ok;
}



void TDEProcess::commClose()
{
  closeStdin();

#ifdef Q_OS_UNIX
  if (pid_) { // detached, failed, and killed processes have no output. basta. :)
    // If both channels are being read we need to make sure that one socket
    // buffer doesn't fill up whilst we are waiting for data on the other
    // (causing a deadlock). Hence we need to use select.

    int notfd = TDEProcessController::theTDEProcessController->notifierFd();

    while ((communication & (Stdout | Stderr)) || runs) {
      fd_set rfds;
      FD_ZERO(&rfds);
      struct timeval timeout, *p_timeout;

      int max_fd = 0;
      if (communication & Stdout) {
        FD_SET(out[0], &rfds);
        max_fd = out[0];
      }
      if (communication & Stderr) {
        FD_SET(err[0], &rfds);
        if (err[0] > max_fd)
          max_fd = err[0];
      }
      if (runs) {
        FD_SET(notfd, &rfds);
        if (notfd > max_fd)
          max_fd = notfd;
        // If the process is still running we block until we
        // receive data or the process exits.
        p_timeout = 0; // no timeout
      } else {
        // If the process has already exited, we only check
        // the available data, we don't wait for more.
        timeout.tv_sec = timeout.tv_usec = 0; // timeout immediately
        p_timeout = &timeout;
      }

      int fds_ready = select(max_fd+1, &rfds, 0, 0, p_timeout);
      if (fds_ready < 0) {
        if (errno == EINTR)
          continue;
        break;
      } else if (!fds_ready)
        break;

      if ((communication & Stdout) && FD_ISSET(out[0], &rfds))
        slotChildOutput(out[0]);

      if ((communication & Stderr) && FD_ISSET(err[0], &rfds))
        slotChildError(err[0]);

      if (runs && FD_ISSET(notfd, &rfds)) {
        runs = false; // hack: signal potential exit
        return; // don't close anything, we will be called again
      }
    }
  }
#endif //Q_OS_UNIX

  closeStdout();
  closeStderr();

  closePty();
}


void TDEProcess::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }


///////////////////////////
// CC: Class KShellProcess
///////////////////////////

KShellProcess::KShellProcess(const char *shellname):
  TDEProcess()
{
  setUseShell( true, shellname ? shellname : getenv("SHELL") );
}

KShellProcess::~KShellProcess() {
}

TQString KShellProcess::quote(const TQString &arg)
{
    return TDEProcess::quote(arg);
}

bool KShellProcess::start(RunMode runmode, Communication comm)
{
  return TDEProcess::start(runmode, comm);
}

void KShellProcess::virtual_hook( int id, void* data )
{ TDEProcess::virtual_hook( id, data ); }

#include "kprocess.moc"