Navrattan Bansal
Navrattan Bansal

Reputation: 169

Runnning SCP in backgroung using Perl CGI

I am Run Perl CGI Script. In which i am running SCP Command. But I want that command to be run into background and exit the script. But Still Web page waiting for Finish the script. I m doing like :

system ("scp -r machinename:/path/to/file/for/copy/ /path/for/destination/directory/  &");

But it is not working fine. Still it is waiting for Finish the script. Please help me out.

And Also Tell me how to get output of SCP on webpage using Perl CGI: I am doing like this:

system ("scp -r machinename:/path/to/file/for/copy/ /path/for/ destination/directory/ 2>&1 &");

Upvotes: 1

Views: 764

Answers (2)

derobert
derobert

Reputation: 51197

When you're running in CGI, the standard filehandles (STDIN, STDOUT, STDERR) all go back to the webserver. You need to close them in your child process:

my $pid = fork();
if (! defined $pid) {
    ...
} elsif (0 == $pid) {
    # child
    close(STDIN);
    close(STDOUT);
    chose(STDERR);
    exec { 'scp' } 'scp', 'file', 'user@host:/path/to/file';
} else {
    ...
}

Alternatively, you can reopen them somewhere more useful (e.g., STDIN from /dev/null, STDOUT and STDERR to your own log file):

open STDIN, '<', '/dev/null'
    or confess "Failed to reopen STDIN";

You can also use FD_CLOEXEC with fcntl (and that'll probably even work if you keep your existing system call instead of changing to explicit fork/exec).

Depending on web server, you may need to do other things (e.g., become session leader with POSIX::setsid.

All of this is conveniently done for you by the Proc::Daemon module.

I suggest you also look at IPC::Run3, especially for when you want to capture scp output and send it to the browser. It'll allow you to easily get that output back into a scalar, which you can then format and print easily.

Upvotes: 1

GO.exe
GO.exe

Reputation: 724

This might help: scp as a background process

and for perl there is another question:

How can I run Perl system commands in the background?

Upvotes: 0

Related Questions