简体   繁体   中英

Perl and external programs

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.

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.

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

Try this instead:

printf("100\n");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM