1System::Command(3) User Contributed Perl Documentation System::Command(3)
2
3
4
6 System::Command - Object for running system commands
7
9 version 1.119
10
12 use System::Command;
13
14 # invoke an external command, and return an object
15 $cmd = System::Command->new( @cmd );
16
17 # options can be passed as a hashref
18 $cmd = System::Command->new( @cmd, \%option );
19
20 # $cmd is basically a hash, with keys / accessors
21 $cmd->stdin(); # filehandle to the process stdin (write)
22 $cmd->stdout(); # filehandle to the process stdout (read)
23 $cmd->stderr(); # filehandle to the process stdout (read)
24 $cmd->pid(); # pid of the child process
25
26 # find out if the child process died
27 if ( $cmd->is_terminated() ) {
28 # the handles are not closed yet
29 # but $cmd->exit() et al. are available if it's dead
30 }
31
32 # done!
33 $cmd->close();
34
35 # exit information
36 $cmd->exit(); # exit status
37 $cmd->signal(); # signal
38 $cmd->core(); # core dumped? (boolean)
39
40 # cut to the chase
41 my ( $pid, $in, $out, $err ) = System::Command->spawn(@cmd);
42
44 System::Command is a class that launches external system commands and
45 return an object representing them, allowing to interact with them
46 through their "STDIN", "STDOUT" and "STDERR" handles.
47
49 System::Command supports the following methods:
50
51 new
52 my $cmd = System::Command->new( @cmd )
53
54 Runs an external command using the list in @cmd.
55
56 If @cmd contains a hash reference, it is taken as an option hash.
57
58 If several option hashes are passed to "new()", they will be merged
59 together with individual values being overridden by those (with the
60 same key) from hashes that appear later in the list.
61
62 To allow subclasses to support their own set of options, unrecognized
63 options are silently ignored.
64
65 The recognized keys are:
66
67 "cwd"
68 The current working directory in which the command will be run.
69
70 "env"
71 A hashref containing key / values to add to the command
72 environment.
73
74 If several option hashes define the "env" key, the hashes they
75 point to will be merged into one (instead of the last one taking
76 precedence).
77
78 If a value is "undef", the variable corresponding to the key will
79 be removed from the environment.
80
81 "input"
82 A string that is send to the command's standard input, which is
83 then closed.
84
85 Using the empty string as "input" will close the command's standard
86 input without writing to it.
87
88 Using "undef" as "input" will not do anything. This behaviour
89 provides a way to modify previous options populated by some other
90 part of the program.
91
92 On some systems, some commands may close standard input on startup,
93 which will cause a SIGPIPE when trying to write to it. This will
94 raise an exception.
95
96 "interactive"
97 If true, the command will actually be run using the "system" in
98 perlfunc builtin. If "STDIN" is not a terminal, the constructor
99 will die.
100
101 Not reaper object will be created, and the "stdin", "stdout" and
102 "stderr" filehandles will point to dummy closed handles. The
103 "exit", "signal" and "core" attributes will be correctly set.
104
105 (Added in version 1.114.)
106
107 "setpgrp"
108 By default, the spawned process is made the leader of its own
109 process group using "setpgrp( 0, 0 )" (if possible). This enables
110 sending a signal to the command and all its child processes at
111 once:
112
113 # negative signal is sent to the process group
114 kill -SIGKILL, $cmd->pid;
115
116 Setting the "setpgrp" option to a false value disables this
117 behaviour.
118
119 (Added in version 1.110.)
120
121 "trace"
122 The "trace" option defines the trace settings for System::Command.
123 The "SYSTEM_COMMAND_TRACE" environment variable can be used to
124 specify a global trace setting at startup. The environment variable
125 overrides individual "trace" options.
126
127 If "trace" or "SYSTEM_COMMAND_TRACE" contains an "=" character then
128 what follows it is used as the name of the file to append the trace
129 to. When using the "trace" option, it is recommended to use an
130 absolute path for the trace file, in case the main program
131 "chdir()" before calling System::Command.
132
133 At trace level 1, only the command line is shown:
134
135 System::Command cmd[12834]: /usr/bin/git commit -m "Test option hash in new()"
136
137 Note: Command-line parameters containing whitespace will be
138 properly quoted.
139
140 At trace level 2, the options values are shown:
141
142 System::Command opt[12834]: cwd => "/tmp/kHkPUBIVWd"
143 System::Command opt[12834]: fatal => {128 => 1,129 => 1}
144 System::Command opt[12834]: git => "/usr/bin/git"
145
146 Note: The "fatal" and "git" options in the example above are
147 actually used by Git::Repository to determine the command to be
148 run, and ignored by System::Command. References are dumped using
149 Data::Dumper.
150
151 At trace level 3, the content of the "env" option is also listed:
152
153 System::Command env[12834]: GIT_AUTHOR_EMAIL => "author\@example.com"
154 System::Command env[12834]: GIT_AUTHOR_NAME => "Example author"
155
156 If the command cannot be spawned, the trace will show "!" instead
157 of the pid:
158
159 System::Command cmd[!]: does-not-exist
160
161 (Added in version 1.108.)
162
163 exit
164 core
165 signal
166 The above three options can be set to point to a reference to a
167 scalar, which will be automatically updated when the command is
168 terminated. See the "Accessors" section for details about what the
169 attributes of the same name mean.
170
171 (Added in version 1.114.)
172
173 The System::Command object returned by "new()" has a number of
174 attributes defined (see below).
175
176 close
177 $cmd->close;
178
179 Close all pipes to the child process, collects exit status, etc. and
180 defines a number of attributes (see below).
181
182 Returns the invocant, so one can do things like:
183
184 my $exit = $cmd->close->exit;
185
186 is_terminated
187 if ( $cmd->is_terminated ) {...}
188
189 Returns a true value if the underlying process was terminated.
190
191 If the process was indeed terminated, collects exit status, etc. and
192 defines the same attributes as "close()", but does not close all pipes
193 to the child process.
194
195 spawn
196 my ( $pid, $in, $out, $err ) = System::Command->spawn(@cmd);
197
198 This shortcut method calls "new()" (and so accepts options in the same
199 manner) and directly returns the "pid", "stdin", "stdout" and "stderr"
200 attributes, in that order.
201
202 (Added in version 1.01.)
203
204 loop_on
205 $cmd->loop_on(
206 stdout => sub { ... },
207 stderr => sub { ... },
208 );
209
210 This method calls the corresponding code references with each line
211 produced on the standard output and errput of the command.
212
213 If the "stdout" or "stderr" argument is not given, the default is to
214 silently drop the data for "stdout", and to pass through (to STDERR)
215 the data for "stderr". To prevent any processing, pass a false value to
216 the parameter.
217
218 For example, the following line will silently run the command to
219 completion:
220
221 $cmd->loop_on( stderr => '' );
222
223 The method blocks until the command is completed (or rather, until its
224 output and errput handles have been closed), or until one of the
225 callbacks returns a false value.
226
227 Data is read using readline, which depends on $/ for its definition of
228 a "line". To that effect, the method takes a third optional argument,
229 "input_record_separator", which sets the value for $/ for the duration
230 of the call.
231
232 Caveat Emptor: since "loop_on" is line-based, it may block if either
233 output or errput sends incomplete lines (e.g. if the command is some
234 sort of interactive shell with a prompt).
235
236 The return value is true if the command exited with status 0, and false
237 otherwise (i.e. the Unix traditional definition of success).
238
239 (Added in version 1.117.)
240
241 Accessors
242 The attributes of a System::Command object are also accessible through
243 a number of accessors.
244
245 The object returned by "new()" will have the following attributes
246 defined:
247
248 cmdline
249 Return the command-line actually executed, as a list of strings.
250
251 options
252 The merged list of options used to run the command.
253
254 pid The PID of the underlying command.
255
256 stdin
257 A filehandle opened in write mode to the child process' standard
258 input.
259
260 stdout
261 A filehandle opened in read mode to the child process' standard
262 output.
263
264 stderr
265 A filehandle opened in read mode to the child process' standard
266 error output.
267
268 Regarding the handles to the child process, note that in the following
269 code:
270
271 my $fh = System::Command->new( @cmd )->stdout;
272
273 $fh is opened and points to the output handle of the child process,
274 while the anonymous System::Command object has been destroyed. Once $fh
275 is destroyed, the subprocess will be reaped, thus avoiding zombies.
276 (System::Command::Reaper undertakes this process.)
277
278 After the call to "close()" or after "is_terminated()" returns true,
279 the following attributes will be defined (note that the accessors
280 always run "is_terminated()", to improve their chance of getting a
281 value if the process just finished):
282
283 exit
284 The exit status of the underlying command.
285
286 signal
287 The signal, if any, that killed the command.
288
289 core
290 A boolean value indicating if the command dumped core.
291
292 Even when not having a reference to the System::Command object any
293 more, it's still possible to get the "exit", "core" or "signal" values,
294 using the options of the same name:
295
296 my $fh = System::Command->new( @cmd, { exit => \my $exit } )->stdout;
297
298 Once the command is terminated, the $exit variable will contain the
299 value that would have been returned by the "exit()" method.
300
302 Note that System::Command uses "waitpid()" to catch the status
303 information of the child processes it starts. This means that if your
304 code (or any module you "use") does something like the following:
305
306 local $SIG{CHLD} = 'IGNORE'; # reap child processes
307
308 System::Command will not be able to capture the "exit", "signal" and
309 "core" attributes. It will instead set all of them to the impossible
310 value "-1", and display the warning "Child process already reaped,
311 check for a SIGCHLD handler".
312
313 To silence this warning (and accept the impossible status information),
314 load System::Command with:
315
316 use System::Command -quiet;
317
318 It is also possible to more finely control the warning by setting the
319 $System::Command::QUIET variable (the warning is not emitted if the
320 variable is set to a true value).
321
322 If the subprocess started by System::Command has a short life
323 expectancy, and no other child process is expected to die during that
324 time, you could even disable the handler locally (use at your own
325 risks):
326
327 {
328 local $SIG{CHLD};
329 my $cmd = System::Command->new(@cmd);
330 ...
331 }
332
334 Philippe Bruhat (BooK), "<book at cpan.org>"
335
337 Thanks to Alexis Sukrieh (SUKRIA) who, when he saw the description of
338 Git::Repository::Command during my talk at OSDC.fr 2010, asked why it
339 was not an independent module. This module was started by taking out of
340 Git::Repository::Command 1.08 the parts that weren't related to Git.
341
342 Thanks to Christian Walde (MITHALDU) for his help in making this module
343 work better under Win32.
344
345 The System::Command::Reaper class was added after the addition of
346 Git::Repository::Command::Reaper in Git::Repository::Command 1.11. It
347 was later removed from System::Command version 1.03, and brought back
348 from the dead to deal with the zombie apocalypse in version 1.106. The
349 idea of a reaper class comes from Vincent Pit.
350
351 Thanks to Tim Bunce for using Git::Repository and making many
352 suggestions based on his use and needs. Most of them turned into
353 improvement for System::Command instead, once we figured out that the
354 more general feature idea really belonged there.
355
357 Please report any bugs or feature requests to "bug-system-command at
358 rt.cpan.org", or through the web interface at
359 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=System-Command>. I
360 will be notified, and then you'll automatically be notified of progress
361 on your bug as I make changes.
362
364 You can find documentation for this module with the perldoc command.
365
366 perldoc System::Command
367
368 You can also look for information at:
369
370 · RT: CPAN's request tracker
371
372 <http://rt.cpan.org/NoAuth/Bugs.html?Dist=System-Command>
373
374 · AnnoCPAN: Annotated CPAN documentation
375
376 <http://annocpan.org/dist/System-Command>
377
378 · CPAN Ratings
379
380 <http://cpanratings.perl.org/d/System-Command>
381
382 · Search CPAN
383
384 <http://search.cpan.org/dist/System-Command/>
385
387 Copyright 2010-2016 Philippe Bruhat (BooK).
388
390 This program is free software; you can redistribute it and/or modify it
391 under the terms of either: the GNU General Public License as published
392 by the Free Software Foundation; or the Artistic License.
393
394 See <http://dev.perl.org/licenses/> for more information.
395
396
397
398perl v5.30.1 2020-01-30 System::Command(3)