Getting PID of external command

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?

On Mon, Mar 12, 2007 at 11:03:09AM +0900, Marc H. wrote:

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 :slight_smile:

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.

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

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

Marc H. schrieb:

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