Saturday, March 14, 2009

Exec with stdout / output redirected

You could have exec feature in your code / application. But if you need to exec with output redirected to a log file it will not work without pipes operations. But there is one trick - exec bash and provide your command with output redirected to a log as parameter to bash.

Syntax:
bash -c "command"

Example:
bash -c "ls -la"

Example with stdout redirected to a log:
bash -c "ls -la > log.txt"

In programming languages usually we have exec with several parameters:
  • path - string
  • args - array

java: Runtime.exec
php: pcntl_exec

So we need to prepare something like next:
  • path = /bin/bash
  • args:
    • arg1 = -c
    • arg2 = "command > log"     or     "command > log 2>&1"

Refer the PHP code below:
<?php
/**
* Execute an external program
* @param string $path path to external program
* @param array $args program arguments
*/

function execute($path, $args) {
return pcntl_exec($path, $args);
}

/**
* Execute an external program with output redirected to log
* @param string $path path to external program
* @param array $args program arguments
* @param string $log log file name
*/

function execute_redir($path, $args, $log) {
$path .= ' '.implode(' ', $args);

$args = array();
$args[] = '-c';
$args[] = $path.' > '.$log.' 2>&1';

$path = '/bin/bash';
execute($path, $args);
}

// execute without output redirected
//execute('/bin/ls', array('-la'));

// execute with output redirected
execute_redir('/bin/ls', array('-la'), 'log.txt');
?>

No comments: