tags:

views:

79

answers:

3

Hi,

I have a Perl program and a C program. I want to run the Perl program and capture the return value of C program. To make it clear:

C program (a.out)

int main()
{
    printf("100");
    return 100;
}

Perl program:

print `ls`; #OK
print `a.out`; #No error but it does not print any output.

Any ideas? Thanks.

+2  A: 

I don't know perl but this works on my system so no guarantees:

#!/usr/bin/perl

print "Running a.out now\n";
$exitCode = system("./a.out");
print "a.out returned:\n";
print $exitCode>>8; print "\n";

For one reason or another system() returns the return value bitshfted by 8 (so 0 will become 256, 1 will be 512... 7 will be 1792 or something like that) but I didn't care to look up why.

btfx
The OP is trying to capture the program's output, not its return value. That's what backticks do.
Ether
@Ether: I didn't know that, but I think he was just using backticks for brevity, and since his question says "I want to run the Perl program and capture the return value of C program." I'm guessing he just wants the return value. If you have any idea how to capture both and only run it once I would be curious.
btfx
See http://stackoverflow.com/questions/109124/how-do-you-capture-stderr-stdout-and-the-exit-code-all-at-once-in-perl
daotoad
@Ether: that's not at all clear
ysth
+1  A: 

Your C program is not printing a carriage return, so you may be seeing line buffering issues.

Try this instead:

printf("100\n");
Ether
A: 

system() will return a code indicating what your C program returned or if it was terminated by a signal; assuming the later is not the case, you can do

$exitcode = system('a.out');
print "return code was ", $exitcode >> 8, "\n";

If you also wish to capture the output, you can use backticks and the code will be in the $? variable.

$output = `a.out`;
$exitcode = $?;
print "return code was ", $exitcode >> 8, "\n";
print "output was:\n", $output;

You may want to use a module like IPC::Cmd that has several other features you may want.

ysth