eweaverp has asked for the wisdom of the Perl Monks concerning the following question:

Hola Monks...

I have some code like this:

my $pid = open(SFTP, '|-', "sftp $hostname > /tmp/_sftplog.txt"); print SFTP "some commands"; close (SFTP); my $pidflag; do { system('sleep 5'); $pidflag = `ps -a \| grep -c \' $pid \'`; chomp($pidflag); } while ($pidflag);
which checks via 'ps' to see if the spawned sFTP process has ended--that is, the grep count of its PID is 0--before moving on (the space is to make sure '1134' doesn't match '11134', etc.). I have two questions:

1) Is this even necessary? Does close() guarantee the process has finished?

2) Is there a less kludgy way to do this? My method seems very crude. I poked around at the $? variable, but it doesn't seem to give me what I want.

Thanks,

~evan

Replies are listed 'Best First'.
Re: Waiting for an external process to end?
by ctilmes (Vicar) on Jul 24, 2003 at 21:08 UTC
    1) close() won't return until the process has finished. From "perldoc -f close":

    Closes the file or pipe associated with the file handle, returning true only if stdio successfully flushes buffers and closes the system file descriptor.

    Closing a pipe also waits for the process executing on the pipe to complete, in case you want to look at the output of the pipe afterwards, and implicitly puts the exit status value of that command into "$?".

    2) try waitpid $pid

    (Update: add perldoc snippet to 1)

Re: Waiting for an external process to end?
by Anonymous Monk on Jul 24, 2003 at 22:43 UTC
    I wonder why you didn't use NET::SFTP? I decided against using it because it was dependent on too many other Perl modules. Just curious if you had the same opinion :)

      Well, not having root access on my Sun network, I try to avoid creating scripts other people need to use that depend on modules installed in my personal /home directory. Although it can't be avoided in some instances.

      So, to answer your question: yes.

      One is too many modules for me if there is an equally easy way to achieve the same functionality.

      ~evan