[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Getting PID of external command

Marc Heiler

3/12/2007 2:03:00 AM

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?

--
Posted via http://www.ruby-....

3 Answers

Brian Candler

3/12/2007 9:08:00 AM

0

On Mon, Mar 12, 2007 at 11:03:09AM +0900, Marc Heiler 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 :-)

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.

Marc Heiler

3/17/2007 8:02:00 AM

0

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?

--
Posted via http://www.ruby-....

Jan Friedrich

3/17/2007 2:37:00 PM

0

Marc Heiler 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