]> git.proxmox.com Git - pve-common.git/blobdiff - data/PVE/Tools.pm
correctly call errfunc inside run_command
[pve-common.git] / data / PVE / Tools.pm
index b42a5bb5f603b4ff5b3d13a9503aabb9067f2a64..33f0de1a217715395c521caf77b218673d9fe51e 100644 (file)
@@ -170,7 +170,7 @@ sub run_command {
 
     $cmd = [ $cmd ] if !ref($cmd);
 
-    my $cmdstr = join (' ', @$cmd);
+    my $cmdstr = cmd2string($cmd);
 
     my $errmsg;
     my $laststderr;
@@ -178,12 +178,13 @@ sub run_command {
     my $oldtimeout;
     my $pid;
 
+    my $outfunc;
+    my $errfunc;
+    my $logfunc;
+    my $input;
+    my $output;
+
     eval {
-       my $input;
-       my $output;
-       my $outfunc;
-       my $errfunc;
-       my $logfunc;
 
        foreach my $p (keys %param) {
            if ($p eq 'timeout') {
@@ -192,10 +193,6 @@ sub run_command {
                umask($param{$p});
            } elsif ($p eq 'errmsg') {
                $errmsg = $param{$p};
-               $errfunc = sub {
-                   print STDERR "$laststderr\n" if $laststderr;
-                   $laststderr = shift; 
-               };
            } elsif ($p eq 'input') {
                $input = $param{$p};
            } elsif ($p eq 'output') {
@@ -211,6 +208,20 @@ sub run_command {
            }
        }
 
+       if ($errmsg) {
+           my $origerrfunc = $errfunc;
+           $errfunc = sub {
+               if ($laststderr) {
+                   if ($origerrfunc) {
+                       &$origerrfunc("$laststderr\n");
+                   } else {
+                       print STDERR "$laststderr\n" if $laststderr;
+                   }
+               }
+               $laststderr = shift; 
+           };
+       }
+
        my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
        my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
        my $error  = IO::File->new();
@@ -353,7 +364,9 @@ sub run_command {
 
     alarm(0);
 
-    print STDERR "$laststderr\n" if $laststderr;
+    if ($errmsg && $laststderr) {
+       &$errfunc(undef); # flush laststderr
+    }
 
     umask ($old_umask) if defined($old_umask);
 
@@ -695,6 +708,19 @@ sub shellquote {
     return String::ShellQuote::shell_quote($str);
 }
 
+sub cmd2string {
+    my ($cmd) = @_;
+
+    die "no arguments" if !$cmd;
+
+    return $cmd if !ref($cmd);
+
+    my @qa = ();
+    foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
+
+    return join (' ', @qa);
+}
+
 # split an shell argument string into an array,
 sub split_args {
     my ($str) = @_;