Getting PID of external command

M

Marc Heiler

Hi there,

I am using

Kernel.system("mplayer foobar.wav")

to play a song. This works, but I also need to be able
to kill it from a script. My idea was to simply
get the PID of the mplayer process, Kernel.system
however does not seem to allow this easily, and
Io.popen doesnt wait for it to have finished.

Is there a way to get the PID?
 
B

Brian Candler

I am using

Kernel.system("mplayer foobar.wav")

to play a song. This works, but I also need to be able
to kill it from a script. My idea was to simply
get the PID of the mplayer process, Kernel.system
however does not seem to allow this easily, and
Io.popen doesnt wait for it to have finished.

There's a chicken-and-egg there. You're asking for the pid to be available
before the command terminates, but you're also asking for the command not to
return until the command terminates :)

Perhaps you want to invoke a callback function with the pid?

You can implement Kernel.system() yourself very easily: it's just a fork and
exec.

def my_system(*cmd)
pid = fork do
exec(*cmd)
exit! 127
end
yield pid if block_given?
Process.waitpid(pid)
$?
end

my_system("sleep 10") { |pid| puts "Pid is #{pid}" }

But I expect IO.popen will be better in many cases, in particular if you
want to capture the stdout of the child process. With system() and the above
code, the child process shares stdout with the parent.

B.
 
M

Marc Heiler

Thanks, I think that does what I need, at least my first test worked. :)

Is there a way to exchange $? with a longer name? Is that $CHILD_STATUS?
 
J

Jan Friedrich

Marc said:
Is there a way to exchange $? with a longer name? Is that $CHILD_STATUS?
Yes, but don't forget to include English!

require 'English'
$CHILD_STATUS


regards
Jan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top