How to start another command in a Ruby program.
Mainly write about popen
Give the command to the system () function as a character string. The easiest.
sys0.rb
system("ls")
When you run
ruby sys0.rb
a.txt b.txt c.txt sys0.rb sys1.rb sys2.rb
sys1.rb
system("ls *.txt")
When you run
ruby sys1.rb
a.txt b.txt c.txt
Exit status (exit status, exit status) can be obtained with $?
sys2.rb
system("ls abc")
print $?, "\n"
When you run
ruby sys2.rb
ls: cannot access abc: No such file or directory pid 13715 exit 2
ls has failed with exit status 2.
You can get and input the output of the executed command (child process). In short, you can read / write to standard I / O.
popen0.rb
IO.popen("ls","r") do | io |
while io.gets do
print
end
end
When you run
ruby popen0.rb
a.txt b.txt c.txt popen0.rb sys0.rb sys1.rb sys2.rb
popen1.rb
IO.popen("grep e","r+") do | io |
io.print "Hello,\n"
io.print "World!\n"
io.close_write
while io.gets do
print
end
end
When you run
ruby popen1.rb
Hello,
fork0.rb
print "Start!\n"
child_pid = fork do
#Only child processes below
print "I am a child. pid=", Process.pid, "\n"
sleep(1)
#Only child processes execute
end
#Only the parent process below
print "I am a parent. my pid=", Process.pid, ", my child's pid=", child_pid, "\n"
Process.waitpid(child_pid) #Wait for the child process to finish
When you run
ruby fork0.rb
Start! I am a parent. my pid=25527, my child's pid=25529 I am a child. pid=25529
fork1.rb
print "Start!\n"
child_pid = fork do
#Only child processes below
exec("ls")
#Only child processes execute
#Not executed below
abc()
#Will not be executed
end
#Only the parent process below
print "I am a parent. my pid=", Process.pid, ", my child's pid=", child_pid, "\n"
Process.waitpid(child_pid) #Wait for the child process to finish
When you run
ruby fork1.rb
Start! I am a parent. my pid=25801, my child's pid=25803 a.txt b.txt c.txt fork0.rb fork1.rb popen0.rb popen1.rb sys0.rb sys1.rb sys2.rb
Recommended Posts