Page 1 of 1

Strange return codes

Posted: Fri Jan 16, 2009 1:06 pm
by georgewr3
I'm using system to call a C++ executable. The executable calls the fork command. The child does some processing in a finite loop. The parent goes to sleep for a time. If the parent wakes up and the child is not done, the parent kills the child and sets the return code to -1. Otherwise the child finishes before the parent and kills the parent and sets the return code to zero.

When I run the C++ executable it does what I expect and finishes with a result of either -1 or 0. When I use the PHP system call, the value of the supplied return code is either 15 or 255. Why?

(PHP 5.2.0, Suse 10.2)

Here's the code:
---------------
C++
---------------
[c]#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>#include <signal.h>using namespace std; int ChildProcess(char*, char*);void ParentProcess(int, char*); int res; int main(int argc, char** argv){    if (argc != 4) {        cerr << endl;        cerr << "usage: ./test <reps> <sleep-time> <child-wait-time>" << endl << endl;        exit(-1);    }     res = 0;       // assume success    pid_t  pid, parent_pid;    parent_pid = getpid();    pid = fork();    if (pid == 0)    {        ChildProcess(argv[1], argv[2]);        kill(parent_pid, SIGTERM);    }    else    {        ParentProcess(pid, argv[3]);        res = -1;    }    printf("   *** res == %d ***\n", res);    return res;} int ChildProcess(char* reps, char* sleeptime){    int i;    for (i = 1; i <= atoi(reps); i++)    {        sleep(atoi(sleeptime));        printf("   This line is from child, value = %d\n", i);    }    printf("   *** Child process is done ***\n");    return 0;} void  ParentProcess(int pid, char* timeout){    sleep(atoi(timeout));    kill(pid, SIGTERM);}[/c]
-------------
PHP
-------------

Code: Select all

#!/usr/bin/php -q
 
<?php
 
$retval = 0;
system('/badger/cspans/test 5 5 30', $retval);
print("\n$retval\n");
 
?>

Re: Strange return codes

Posted: Fri Jan 16, 2009 1:34 pm
by RobertGonzalez
Not that it would make a world of difference, but have you tried something like:

file.php

Code: Select all

<?php
$ret = `/badger/cspans/test 5 5 30`;
print $ret;
?>
Then calling it from the CLI like:

Code: Select all

 
$] php file.php
 

Re: Strange return codes

Posted: Fri Jan 16, 2009 1:42 pm
by georgewr3
I didn't think of that however when I tried it, return code is empty.

Re: Strange return codes

Posted: Fri Jan 16, 2009 2:23 pm
by georgewr3
My intent is to be able to abort from calling the PHP system api after a predetermined amount of time in case the native code hangs forever for some reason.

Is there a simpler way to do this?