Run a program with OSProcess
Jump to navigation
Jump to search
As before, but pass input through
All the sinppets in this page require you to run
Feature require: 'OSProcess'.
Simple. Run a command and wait, only for the output
- sync
- Main issue. no exit code.
Example. ---- NO - move it out from here, requires CommandShell
out _ OSProcess outputOf: 'pwd'. out class. "=> String " out withBlanksTrimmed. "=> '/home/p/prog/cuis-project' "
Simple. Run a command and wait, only to get the exit code
- sync
- Main issue. not frequently useful.
Example
out _ OSProcess waitForCommand: ' sh -c "exit 33" '. out class. "=> ExternalUnixOSProcess " out exitCode . "=> 33 . NOTE. exitCode was added on 16-oct-2021."
Run a command to get the output, no input, sync
Example. Get the current date using Linux date command.
d _ Delay forMilliseconds: 50.
in _ nil.
out _ '/tmp/test.out' asFileEntry forceWriteStream .
err _ '/tmp/test.err' asFileEntry forceWriteStream .
proc _ UnixProcess forkJob: '/usr/bin/date'
arguments: nil environment: nil
descriptors: {in. out. err.}.
[proc runState == #complete] whileFalse: [d wait].
proc pid.
oExit _ proc exitCode .
oOut _ out contents.
oErr _ err contents.
{in. out. err} do: [ :f | f ifNotNil: [ f close ] ].
'exitCode: {1}, output: {2}' format: {oExit. oOut withBlanksTrimmed .}
"=> 'exitCode: 0, output: Tue 14 Sep 16:23:10 CEST 2021' "
Run a command through the shell to get the output, no input, sync
Example. Get the first 3 lines of output of ls in the current directory. That is run in bash the
command ls -l | head -n 3.
d _ Delay forMilliseconds: 50.
in _ nil.
out _ '/tmp/test.out' asFileEntry forceWriteStream .
err _ '/tmp/test.err' asFileEntry forceWriteStream .
proc _ UnixProcess forkJob: '/usr/bin/bash'
arguments: {'-c'. 'ls -l | head -n 3'}
environment: nil
descriptors: {in. out. err.}.
[proc runState == #complete] whileFalse: [d wait].
proc pid.
oExit _ proc exitCode .
oOut _ out contents.
oErr _ err contents.
{in. out. err} do: [ :f | f ifNotNil: [ f close ] ].
'exitCode: %d\noutput: %s' printf: {oExit. oOut withBlanksTrimmed } .
"=> 'exitCode: 0
output: total 3808
drwxrwx--- 3 p p 4096 Aug 18 12:54 AMQP
drwxrwx--- 3 p p 4096 Aug 18 12:54 Cairo' "
As before, but pass input through stdin
Example. We are going to count the number of charaters of what is sent through stdin via wc -c.
d _ Delay forMilliseconds: 50.
'/tmp/test.in' asFileEntry fileContents: 'Hello World!'.
in _ '/tmp/test.in' asFileEntry readStream .
out _ '/tmp/test.out' asFileEntry forceWriteStream .
err _ '/tmp/test.err' asFileEntry forceWriteStream .
proc _ UnixProcess forkJob: '/usr/bin/bash'
arguments: {'-c'. 'wc -c'}
environment: nil
descriptors: {in. out. err.}.
[proc runState == #complete] whileFalse: [d wait].
proc pid.
oExit _ proc exitCode .
oOut _ out contents.
oErr _ err contents.
{in. out. err} do: [ :f | f ifNotNil: [ f close ] ].
'exitCode: %d\noutput: %s' printf: {oExit. oOut withBlanksTrimmed } .
"=> 'exitCode: 0
output: 12' "