FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
rstudio/src/cpp/core/system/PosixChildProcess.cpp at main · ssh352/rstudio · GitHub
ssh352
/
rstudio
Public
forked from
rstudio/rstudio
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
rstudio
/
src
/
cpp
/
core
/
system
/
PosixChildProcess.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
1882 lines (1616 loc) · 54.9 KB
Breadcrumbs
rstudio
/
src
/
cpp
/
core
/
system
/
PosixChildProcess.cpp
Copy path
File metadata and controls
1882 lines (1616 loc) · 54.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* PosixChildProcess.cpp
*
* Copyright (C) 2022 by Posit Software, PBC
*
* Unless you have received this program directly from Posit Software pursuant
* to the terms of a commercial license agreement with Posit Software, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#
include
"
ChildProcessSubprocPoll.hpp
"
#
include
<
atomic
>
#
include
<
fcntl.h
>
#
include
<
signal.h
>
#
include
<
unistd.h
>
#
ifdef
__APPLE__
#
include
<
util.h
>
#
include
<
sys/ttycom.h
>
#
include
<
sys/ioctl.h
>
#
elif
defined(__linux__)
#
include
<
pty.h
>
#
include
<
asm/ioctls.h
>
#
include
<
sys/prctl.h
>
#
endif
#
include
<
sys/wait.h
>
#
include
<
sys/types.h
>
#
include
<
boost/asio.hpp
>
#
include
<
boost/bind/bind.hpp
>
#
include
<
shared_core/Error.hpp
>
#
include
<
core/Log.hpp
>
#
include
<
core/PerformanceTimer.hpp
>
#
include
<
core/Thread.hpp
>
#
include
<
core/system/PosixChildProcess.hpp
>
#
include
<
core/system/PosixSystem.hpp
>
#
include
<
core/system/PosixUser.hpp
>
#
include
<
core/system/ProcessArgs.hpp
>
#
include
<
core/system/ShellUtils.hpp
>
using
namespace
boost
::placeholders
;
namespace
rstudio
{
namespace
core
{
namespace
system
{
namespace
{
//
pipe handle indexes
const
int
READ
=
0
;
const
int
WRITE
=
1
;
const
std::
size_t
READ_ERR
= -
1
;
//
how long we keep "saw activity" state at true even if we haven't seen
//
new activity
const
boost::posix_time::milliseconds
kResetRecentDelay
=
boost::posix_time::milliseconds
(
1000
);
//
how often we update "has subprocesses" flag
const
boost::posix_time::milliseconds
kCheckSubprocDelay
=
boost::posix_time::milliseconds
(
200
);
//
how often we query and store current working directory of subprocess
const
boost::posix_time::milliseconds
kCheckCwdDelay
=
boost::posix_time::milliseconds
(
2000
);
int
resolveExitStatus
(
int
status)
{
if
(
WIFEXITED
(status))
{
return
WEXITSTATUS
(status);
}
else
if
(
WIFSIGNALED
(status))
{
//
return bash-style exit codes for process terminated by a signal
//
ex: if killed with SIGTERM, returns 128 + 15 = 143
return
128
+
WTERMSIG
(status);
}
else
return
status;
}
void
setPipeNonBlocking
(
int
pipeFd)
{
int
flags = ::
fcntl
(pipeFd,
F_GETFL
);
if
( (flags != -
1
) && !(flags &
O_NONBLOCK
) )
::fcntl
(pipeFd,
F_SETFL
, flags |
O_NONBLOCK
);
}
void
closePipe
(
int
pipeFd,
const
ErrorLocation& location)
{
safePosixCall<
int
>(
boost::bind
(::close, pipeFd), location);
}
void
closePipe
(
int
* pipeDescriptors,
const
ErrorLocation& location)
{
closePipe
(pipeDescriptors[
READ
], location);
closePipe
(pipeDescriptors[
WRITE
], location);
}
Error
readPipe
(
int
pipeFd, std::string* pOutput,
bool
*pEOF =
nullptr
)
{
//
default to not eof
if
(pEOF)
*pEOF =
false
;
//
setup and read into buffer
const
std::
size_t
kBufferSize
=
512
;
char
buffer[
kBufferSize
];
std::
size_t
bytesRead = posix::posixCall<std::
size_t
>(
boost::bind
(::read, pipeFd, buffer,
kBufferSize
));
while
(
true
)
{
//
check for error
if
(bytesRead ==
READ_ERR
)
{
if
(errno ==
EAGAIN
)
//
carve-out for O_NONBLOCK pipes
return
Success
();
//
on linux slave terminals return EIO rather than bytesRead == 0
//
to indicate end of file
else
if
((errno ==
EIO
) && ::
isatty
(pipeFd))
{
if
(pEOF)
*pEOF =
true
;
return
Success
();
}
else
return
systemError
(errno,
ERROR_LOCATION
);
}
//
check for eof
else
if
(bytesRead ==
0
)
{
if
(pEOF)
*pEOF =
true
;
return
Success
();
}
//
append to output
pOutput->
append
(buffer, bytesRead);
//
read more bytes
bytesRead = posix::posixCall<std::
size_t
>(
boost::bind
(::read, pipeFd, buffer,
kBufferSize
));
}
//
keep compiler happy
return
Success
();
}
}
//
anonymous namespace
struct
ChildProcess
::Impl
{
Impl
() :
pid
(-
1
),
fdStdin
(-
1
),
fdStdout
(-
1
),
fdStderr
(-
1
),
fdMaster
(-
1
),
ctrlC
(
0x03
)
{
}
PidType pid;
int
fdStdin;
int
fdStdout;
int
fdStderr;
//
pty related
int
fdMaster;
char
ctrlC;
void
init
(PidType pid,
int
fdStdin,
int
fdStdout,
int
fdStderr)
{
this
->
pid
= pid;
this
->
fdStdin
= fdStdin;
this
->
fdStdout
= fdStdout;
this
->
fdStderr
= fdStderr;
this
->
fdMaster
= -
1
;
}
void
init
(PidType pid,
int
fdMaster)
{
this
->
pid
= pid;
this
->
fdStdin
= fdMaster;
this
->
fdStdout
= fdMaster;
this
->
fdStderr
= -
1
;
this
->
fdMaster
= fdMaster;
}
void
closeAll
(
const
ErrorLocation &location)
{
closeAll
(
true
, location);
}
void
closeAll
(
bool
clearPid,
const
ErrorLocation& location)
{
if
(clearPid)
pid = -
1
;
if
(fdMaster != -
1
)
{
closeFD
(&fdMaster, location);
fdStdin = -
1
;
fdStdout = -
1
;
}
else
{
closeFD
(&fdStdin, location);
closeFD
(&fdStdout, location);
closeFD
(&fdStderr, location);
}
}
void
closeFD
(
int
* pFD,
const
ErrorLocation& location)
{
if
(*pFD >=
0
)
{
closePipe
(*pFD, location);
*pFD = -
1
;
}
}
};
ChildProcess::ChildProcess
()
: pImpl_(
new
Impl())
{
}
void
ChildProcess::init
(
const
std::string& exe,
const
std::vector<std::string>& args,
const
ProcessOptions& options)
{
exe_ = exe;
args_ = args;
options_ = options;
}
void
ChildProcess::init
(
const
std::string& command,
const
ProcessOptions& options)
{
std::vector<std::string> args;
args.
push_back
(
"
-c
"
);
std::string realCommand = command;
if
(!options.
stdOutFile
.
isEmpty
())
realCommand +=
"
>
"
+
shell_utils::escape
(options.
stdOutFile
);
if
(!options.
stdErrFile
.
isEmpty
())
realCommand +=
"
2>
"
+
shell_utils::escape
(options.
stdErrFile
);
args.
push_back
(realCommand);
init
(
"
/bin/sh
"
, args, options);
}
//
Initialize for an interactive terminal
void
ChildProcess::init
(
const
ProcessOptions& options)
{
if
(!options.
stdOutFile
.
isEmpty
() || !options.
stdErrFile
.
isEmpty
())
{
LOG_ERROR_MESSAGE
(
"
stdOutFile/stdErrFile options cannot be used with interactive terminal
"
);
}
options_ = options;
exe_ = options_.
shellPath
.
getAbsolutePath
();
args_ = options_.
args
;
}
ChildProcess::~ChildProcess
()
{
}
Error
ChildProcess::writeToStdin
(
const
std::string& input,
bool
eof)
{
std::
size_t
written;
Error error = posix::posixCall<std::
size_t
>(
boost::bind
(
::write,
pImpl_->
fdStdin
,
input.
c_str
(),
input.
length
()),
ERROR_LOCATION
,
&written);
if
(error)
return
error;
//
close if requested
if
(eof)
pImpl_->
closeFD
(&pImpl_->
fdStdin
,
ERROR_LOCATION
);
//
check for correct bytes written
if
(written !=
static_cast
<std::
size_t
>(input.
length
()))
return
systemError
(boost::system::errc::io_error,
ERROR_LOCATION
);
//
return success
return
Success
();
}
Error
ChildProcess::ptySetSize
(
int
cols,
int
rows)
{
//
verify we are dealing with a pseudoterminal
if
(!
options
().
pseudoterminal
)
return
systemError
(boost::system::errc::not_supported,
ERROR_LOCATION
);
//
define winsize structure
struct
winsize
winp;
winp.
ws_col
= cols;
winp.
ws_row
= rows;
winp.
ws_xpixel
=
0
;
winp.
ws_ypixel
=
0
;
//
set it
int
res = ::
ioctl
(pImpl_->
fdMaster
,
TIOCSWINSZ
, &winp);
if
(res == -
1
)
return
systemError
(errno,
ERROR_LOCATION
);
else
return
Success
();
}
Error
ChildProcess::ptyInterrupt
()
{
//
verify we are dealing with a pseudoterminal
if
(!
options
().
pseudoterminal
)
return
systemError
(boost::system::errc::not_supported,
ERROR_LOCATION
);
//
write control-c to the slave
return
posix::posixCall<
int
>(
boost::bind
(
::write,
pImpl_->
fdMaster
,
&pImpl_->
ctrlC
,
sizeof
(pImpl_->
ctrlC
)),
ERROR_LOCATION
);
}
PidType
ChildProcess::getPid
()
{
return
pImpl_->
pid
;
}
Error
ChildProcess::terminate
()
{
//
only send signal if the process is open
if
(pImpl_->
pid
== -
1
)
return
systemError
(
ESRCH
,
ERROR_LOCATION
);
//
special code path for pseudoterminal
if
(options_.
pseudoterminal
)
{
#
ifndef
__APPLE__
//
On Linux only do this if dealing with a Terminal-pane process.
//
This is to reduce scope of this change for 1.1
//
TODO: review post 1.1
if
(
options
().
smartTerminal
)
{
#endif
//
you need to close all of the terminal handles to get
//
bash to quit, however some other processes (like svn+ssh
//
require the signal)
pImpl_->
closeAll
(
false
,
ERROR_LOCATION
);
#
ifndef
__APPLE__
}
#
endif
if
(::
killpg
(::
getpgid
(pImpl_->
pid
),
SIGTERM
) == -
1
)
{
if
(errno ==
EPERM
)
//
see note below on carve out for EPERM
return
Success
();
else
return
systemError
(errno,
ERROR_LOCATION
);
}
else
return
Success
();
}
else
{
//
determine target pid (kill just this pid or pid + children)
PidType pid = pImpl_->
pid
;
if
(options_.
detachSession
|| options_.
terminateChildren
)
{
pid = -pid;
}
//
send signal
if
(::
kill
(pid,
SIGTERM
) == -
1
)
{
//
when killing an entire process group EPERM can be returned if even
//
a single one of the subprocesses couldn't be killed. in this case
//
the signal is still delivered and other subprocesses may have been
//
killed so we don't log an error
if
(pid <
0
&& errno ==
EPERM
)
return
Success
();
else
if
(errno ==
ESRCH
)
return
Success
();
else
return
systemError
(errno,
ERROR_LOCATION
);
}
else
return
Success
();
}
}
bool
ChildProcess::hasNonIgnoredSubprocess
()
const
{
//
base class doesn't support subprocess-checking; override to implement
return
true
;
}
bool
ChildProcess::hasIgnoredSubprocess
()
const
{
//
base class doesn't support subprocess-checking; override to implement
return
false
;
}
core::FilePath
ChildProcess::getCwd
()
const
{
//
base class doesn't support cwd-tracking; override to implement
return
FilePath
();
}
bool
ChildProcess::hasRecentOutput
()
const
{
//
base class doesn't support output tracking; override to implement
return
true
;
}
Error
ChildProcess::run
()
{
//
declarations
PidType pid =
0
;
int
fdInput[
2
] = {
0
,
0
};
int
fdOutput[
2
] = {
0
,
0
};
int
fdError[
2
] = {
0
,
0
};
int
fdCloseFd[
2
] = {
0
,
0
};
int
fdMaster =
0
;
//
build args (on heap so they stay around after exec)
//
create set of args to pass (needs to include the cmd)
//
this is done before calling fork as it is unsafe to use fork in multithreaded programs
//
as any calls to malloc could potentially deadlock the child
std::vector<std::string> args;
args.
push_back
(exe_);
args.
insert
(args.
end
(), args_.
begin
(), args_.
end
());
using
core::system::ProcessArgs;
ProcessArgs* pProcessArgs =
new
ProcessArgs
(args);
ProcessArgs* pEnvironment =
nullptr
;
//
get rlimit for max files
//
in the thread-safe fork approach, this needs to be provided
//
to the child to properly close its files in an async-safe way
RLimitType soft, hard;
Error error =
core::system::getResourceLimit
(core::system::FilesLimit, &soft, &hard);
if
(error)
return
error;
if
(options_.
environment
)
{
//
build env (on heap, see comment above)
std::vector<std::string> env;
const
Options& options = options_.
environment
.
get
();
for
(Options::const_iterator
it = options.
begin
(); it != options.
end
(); ++it)
{
env.
push_back
(it->
first
+
"
=
"
+ it->
second
);
}
pEnvironment =
new
ProcessArgs
(env);
}
boost::optional<
uid_t
> runAsUser;
if
(options_.
threadSafe
&& !options_.
runAsUser
.
empty
())
{
//
fetch the user to switch to before forking, as the method is not
//
async signal safe and could cause lockups
core::system::User user;
if
(options_.
runAsUser
==
"
root
"
)
error =
User::getUserFromIdentifier
(
0
, user);
else
error =
User::getUserFromIdentifier
(options_.
runAsUser
, user);
if
(error)
return
error;
runAsUser = user.
getUserId
();
}
if
(options_.
threadSafe
&& options_.
pseudoterminal
)
{
return
systemError
(boost::system::errc::operation_not_supported,
"
Usage of threadSafe and pseudoterminal options together is not supported
"
,
ERROR_LOCATION
);
}
//
pseudoterminal mode: fork using the special forkpty call
if
(options_.
pseudoterminal
)
{
char
* nullName =
nullptr
;
struct
termios
* nullTermp =
nullptr
;
struct
winsize
winSize;
winSize.
ws_col
= options_.
pseudoterminal
.
get
().
cols
;
winSize.
ws_row
= options_.
pseudoterminal
.
get
().
rows
;
winSize.
ws_xpixel
=
0
;
winSize.
ws_ypixel
=
0
;
Error error = posix::posixCall<PidType>(
boost::bind
(::forkpty, &fdMaster, nullName, nullTermp, &winSize),
ERROR_LOCATION
,
&pid);
if
(error)
return
error;
}
//
standard mode: use conventional fork + stream redirection
else
{
//
standard input
Error error = posix::posixCall<
int
>(
boost::bind
(::pipe, fdInput),
ERROR_LOCATION
);
if
(error)
return
error;
//
standard output
error = posix::posixCall<
int
>(
boost::bind
(::pipe, fdOutput),
ERROR_LOCATION
);
if
(error)
{
closePipe
(fdInput,
ERROR_LOCATION
);
return
error;
}
//
standard error
error = posix::posixCall<
int
>(
boost::bind
(::pipe, fdError),
ERROR_LOCATION
);
if
(error)
{
closePipe
(fdInput,
ERROR_LOCATION
);
closePipe
(fdOutput,
ERROR_LOCATION
);
return
error;
}
//
close fd communication channel - only used in threadsafe mode
if
(options_.
threadSafe
)
{
error = posix::posixCall<
int
>(
boost::bind
(::pipe, fdCloseFd),
ERROR_LOCATION
);
if
(error)
{
closePipe
(fdInput,
ERROR_LOCATION
);
closePipe
(fdOutput,
ERROR_LOCATION
);
closePipe
(fdError,
ERROR_LOCATION
);
return
error;
}
}
//
fork
error = posix::posixCall<PidType>(::fork,
ERROR_LOCATION
, &pid);
if
(error)
{
closePipe
(fdInput,
ERROR_LOCATION
);
closePipe
(fdOutput,
ERROR_LOCATION
);
closePipe
(fdError,
ERROR_LOCATION
);
return
error;
}
}
//
child
if
(pid ==
0
)
{
//
NOTE: within the child we want to make sure in all cases that
//
we call ::execv to execute the program. as a result if any
//
errors occur while we are setting up for the ::execv we log
//
and continue rather than calling ::exit (we do this to avoid
//
strange error conditions related to global c++ objects being
//
torn down in a non-standard sequence).
if
(!options_.
threadSafe
)
{
//
note: forking is dangerous in a multithreaded environment
//
the following code uses functions that are not async signal-safe
//
(see http://man7.org/linux/man-pages/man7/signal-safety.7.html)
//
if you spawn children within a multithreaded process, you MUST
//
set threadSafe to true on process options, which provides much less
//
functionality but guarantees that the child will not hang
//
change user here if requested
if
(!options_.
runAsUser
.
empty
())
{
//
restore root
Error error =
core::system::restorePriv
();
if
(error)
LOG_ERROR
(error);
if
(options_.
runAsUser
!=
"
root
"
)
{
//
switch user if not root
error =
core::system::permanentlyDropPriv
(options_.
runAsUser
);
if
(error)
LOG_ERROR
(error);
}
}
//
check for an onAfterFork function
if
(options_.
onAfterFork
)
options_.
onAfterFork
();
//
if we didn't create a pseudoterminal then check the detachSession
//
and terminateChildren options to see whether we need to setsid
//
or setpgid(0,0). we skip the check for pseudoterminals because
//
forkpty calls setsid internally
if
(!options_.
pseudoterminal
)
{
//
If options.detachSession is requested then separate.
if
(options_.
detachSession
)
{
if
(::
setsid
() == -
1
)
{
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
//
intentionally fail forward (see note above)
}
}
else
if
(options_.
terminateChildren
)
{
//
No need to call ::setpgid(0,0) if ::setsid() was already called
//
if options.terminateChildren is requested then obtain a new
//
process group (using our own process id). this enables terminate
//
to specify -pid to kill which will kill this process and all of
//
its children. note that another side-effect is that this process
//
will not automatically die with its parent, so the parent
//
may want to kill all children from the processSupervisor on exit
if
(::
setpgid
(
0
,
0
) == -
1
)
{
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
//
intentionally fail forward (see note above)
}
}
}
//
clear the child signal mask
Error error =
core::system::clearSignalMask
();
if
(error)
{
LOG_ERROR
(error);
//
intentionally fail forward (see note above)
}
//
pseudoterminal mode: file descriptor work is already handled
//
by forkpty, all we need to do is configure terminal behavior
if
(options_.
pseudoterminal
)
{
//
get current attributes
struct
termios
termp;
Error error = posix::posixCall<
int
>(
boost::bind
(::tcgetattr,
STDIN_FILENO
, &termp),
ERROR_LOCATION
);
if
(!error)
{
if
(!options_.
smartTerminal
)
{
//
Specify raw mode; not doing this for terminal (versus dumb
//
shell) because on Linux, it broke things like "passwd"
//
command's ability to collect passwords).
::cfmakeraw
(&termp);
}
else
{
//
for smart terminals we need to echo back the user input
termp.
c_lflag
|=
ECHO
;
termp.
c_oflag
|=
OPOST
|
ONLCR
;
//
Turn off XON/XOFF flow control so Ctrl+S can be used by
//
the shell command-line editing instead of suspending output.
termp.
c_iflag
&= ~(
IXON
|
IXOFF
);
}
//
Don't ignore signals -- this is done
//
so we can send Ctrl-C for interrupts
termp.
c_lflag
|=
ISIG
;
//
set attribs
safePosixCall<
int
>(
boost::bind
(::tcsetattr,
STDIN_FILENO
,
TCSANOW
, &termp),
ERROR_LOCATION
);
//
save the VINTR character
pImpl_->
ctrlC
= termp.
c_cc
[
VINTR
];
}
else
{
LOG_ERROR
(error);
}
}
//
standard mode: close/redirect pipes
else
{
//
close unused pipes -- intentionally fail forward (see note above)
closePipe
(fdInput[
WRITE
],
ERROR_LOCATION
);
closePipe
(fdOutput[
READ
],
ERROR_LOCATION
);
closePipe
(fdError[
READ
],
ERROR_LOCATION
);
//
wire standard streams (intentionally fail forward)
safePosixCall<
int
>(
boost::bind
(::dup2, fdInput[
READ
],
STDIN_FILENO
),
ERROR_LOCATION
);
safePosixCall<
int
>(
boost::bind
(::dup2, fdOutput[
WRITE
],
STDOUT_FILENO
),
ERROR_LOCATION
);
safePosixCall<
int
>(
boost::bind
(::dup2,
options_.
redirectStdErrToStdOut
? fdOutput[
WRITE
]
: fdError[
WRITE
],
STDERR_FILENO
),
ERROR_LOCATION
);
}
//
close all open file descriptors other than std streams
error =
core::system::closeNonStdFileDescriptors
();
if
(error)
{
LOG_ERROR
(error);
//
intentionally fail forward (see note above)
}
if
(!options_.
workingDir
.
isEmpty
())
{
if
(::
chdir
(options_.
workingDir
.
getAbsolutePath
().
c_str
()))
{
std::string message =
"
Error changing directory: '
"
;
message += options_.
workingDir
.
getAbsolutePath
().
c_str
();
message +=
"
'
"
;
LOG_ERROR
(
systemError
(errno, message.
c_str
(),
ERROR_LOCATION
));
}
}
}
else
{
//
note: forking is dangerous in a multithreaded environment (see note above)
//
this block must ONLY use async signal-safe functions and CANNOT
//
dynamically allocate ANY memory or take locks of any kind
//
//
if an error occurs, we exit immediately as this is a critical error
//
we use the form of exit, _exit, which forcefully tears down the process
//
and does not attempt to run c++ cleanup code (as noted problematic above)
if
(runAsUser)
{
if
(
signal_safe::permanentlyDropPriv
(runAsUser.
get
()) == -
1
)
::_exit
(errno);
}
if
(options_.
detachSession
)
{
if
(::
setsid
() == -
1
)
::_exit
(errno);
}
else
if
(options_.
terminateChildren
)
{
if
(::
setpgid
(
0
,
0
) == -
1
)
::_exit
(errno);
}
//
clear signal mask so that child process does not unintentionally
//
block any signals that our parent is blocking
if
(
signal_safe::clearSignalMask
() !=
0
)
::_exit
(errno);
//
close pipe end that we do not need
//
this is not critical and as such, is best effort
//
no error checking is done as a result
::close
(fdInput[
WRITE
]);
::close
(fdOutput[
READ
]);
::close
(fdError[
READ
]);
::close
(fdCloseFd[
WRITE
]);
//
wire standard streams
int
result = ::
dup2
(fdInput[
READ
],
STDIN_FILENO
);
if
(result == -
1
)
::_exit
(errno);
result = ::
dup2
(fdOutput[
WRITE
],
STDOUT_FILENO
);
if
(result == -
1
)
::_exit
(errno);
result = ::
dup2
(options_.
redirectStdErrToStdOut
? fdOutput[
WRITE
] : fdError[
WRITE
],
STDERR_FILENO
);
if
(result == -
1
)
::_exit
(errno);
//
close inherited file descriptors - this prevents
//
the child from clobbering the parent's FDs
//
and actually prevents potential missed child exits caused by
//
clobbering of FDs affecting epoll calls
signal_safe::closeFileDescriptorsFromParent
(fdCloseFd[
READ
],
STDERR_FILENO
+
1
, hard);
::close
(fdCloseFd[
READ
]);
}
if
(options_.
exitWithParent
)
{
#
ifndef
__APPLE__
//
set a bit indicating we want to die when our parent dies
if
(::
prctl
(
PR_SET_PDEATHSIG
,
SIGTERM
) == -
1
)
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
#
endif
}
if
(options_.
environment
)
{
//
execute
::execve
(exe_.c_str(), pProcessArgs->args(), pEnvironment->args());
}
else
{
//
execute
::execv
(exe_.c_str(), pProcessArgs->args());
}
if
(!options_.
threadSafe
)
{
//
in the normal case control should never return from execv (it starts
//
anew at main of the process pointed to by path). therefore, if we get
//
here then there was an error
Error error =
systemError
(errno,
ERROR_LOCATION
);
error.
addProperty
(
"
exe
"
, exe_);
LOG_ERROR
(error);
::exit
(
EXIT_FAILURE
);
}
else
::_exit
(errno);
}
//
parent
else
{
//
pseudoterminal mode: wire input/output streams to fdMaster
//
returned from forkpty
if
(options_.
pseudoterminal
)
{
//
record masterFd as our handles
pImpl_->
init
(pid, fdMaster);
}
//
standard mode: close unused pipes & wire streams to appropriate fds
else
{
//
close unused pipes
closePipe
(fdInput[
READ
],
ERROR_LOCATION
);
closePipe
(fdOutput[
WRITE
],
ERROR_LOCATION
);
closePipe
(fdError[
WRITE
],
ERROR_LOCATION
);
if
(options_.
threadSafe
)
{
closePipe
(fdCloseFd[
READ
],
ERROR_LOCATION
);
}
//
record pipe handles
pImpl_->
init
(pid, fdInput[
WRITE
], fdOutput[
READ
], fdError[
READ
]);
}
delete
pProcessArgs;
delete
pEnvironment;
if
(options_.
threadSafe
)
{
//
send the list of the child proc's fds to the child so
//
it can properly close its unneeded fds in a fast manner
Error error =
closeChildFileDescriptorsFrom
(pid, fdCloseFd[
WRITE
],
STDERR_FILENO
+
1
);
if
(error)
{
//
we simply log the error instead of returning it because it did not prevent
//
us from spawning the process
LOG_ERROR
(error);
}
closePipe
(fdCloseFd[
WRITE
],
ERROR_LOCATION
);
}
return
Success
();
}
//
keep compiler happy
return
Success
();
}
Error
SyncChildProcess::readStdOut
(std::string* pOutput)
{
return
readPipe
(pImpl_->
fdStdout
, pOutput);
}
Error
SyncChildProcess::readStdErr
(std::string* pOutput)
{
return
readPipe
(pImpl_->
fdStderr
, pOutput);
}
Error
SyncChildProcess::waitForExit
(
int
* pExitStatus)
{
//
blocking wait for exit
int
status;
PidType result = posix::posixCall<PidType>(
boost::bind
(::waitpid, pImpl_->
pid
, &status,
0
));
//
always close all of the pipes
pImpl_->
closeAll
(
ERROR_LOCATION
);
//
check result
if
(result == -
1
)
{
*pExitStatus = -
1
;
if
(errno ==
ECHILD
)
//
carve out for child already reaped
return
Success
();
else
return
systemError
(errno,
ERROR_LOCATION
);
}
else
{
*pExitStatus =
resolveExitStatus
(status);
return
Success
();
}
}
struct
AsyncChildProcess
::AsyncImpl
{
AsyncImpl
()
: calledOnStarted_(
false
),
finishedStdout_
(
false
),
finishedStderr_(
false
),
exited_(
false
)
{
}
bool
calledOnStarted_;
bool
finishedStdout_;
bool
finishedStderr_;
bool
exited_;
boost::scoped_ptr<ChildProcessSubprocPoll> pSubprocPoll_;
};
AsyncChildProcess::AsyncChildProcess
(
const
std::string& exe,
const
std::vector<std::string>& args,
const
ProcessOptions& options)
: ChildProcess(), pAsyncImpl_(
new
AsyncImpl())
{
init
(exe, args, options);
if
(!options.
stdOutFile
.
isEmpty
() || !options.
stdErrFile
.
isEmpty
())
{
LOG_WARNING_MESSAGE
(
"
stdOutFile/stdErrFile options cannot be used with runProgram
"
);
}
}
AsyncChildProcess::AsyncChildProcess
(
const
std::string& command,
const
ProcessOptions& options)
: ChildProcess(), pAsyncImpl_(
new
AsyncImpl())
{
init
(command, options);
}
AsyncChildProcess::AsyncChildProcess
(
const
ProcessOptions& options)
: ChildProcess(), pAsyncImpl_(
new
AsyncImpl())
{
init
(options);
}
AsyncChildProcess::~AsyncChildProcess
()
{
}
Error
AsyncChildProcess::terminate
()
{
#
ifndef
__APPLE__
//
On Linux only do this if dealing with a Terminal-pane process.
//
This is to reduce scope of this change for 1.1
//
TODO: review post 1.1
if
(
options
().
smartTerminal
)
{
#endif
if
(
options
().
pseudoterminal
)
{
pAsyncImpl_->
finishedStderr_
=
true
;
pAsyncImpl_->
finishedStdout_
=
true
;
}
#
ifndef
__APPLE__
}
#
endif
return
ChildProcess::terminate
();
}
bool
AsyncChildProcess::hasNonIgnoredSubprocess
()
const
{
if
(pAsyncImpl_->
pSubprocPoll_
)
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL