简体   繁体   English

Perl和外部程序

[英]Perl and external programs

I have a Perl program and a C program. 我有一个Perl程序和一个C程序。 I want to run the Perl program and capture the return value of C program. 我想运行Perl程序并捕获C程序的返回值。 To make it clear: 明确说明:

C program (a.out) C程序(a.out)

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

Perl program: Perl程序:

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: 我不知道perl,但这在我的系统上有效,因此不能保证:

#!/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. 由于一个原因或另一个system()返回由bithfted 8组成的返回值(因此0将变成256,1将成为512 ... 7将成为1792或类似的东西),但是我不在乎查找原因。

Your C program is not printing a carriage return, so you may be seeing line buffering issues. 您的C程序没有打印回车符,因此您可能会看到行缓冲问题。

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; system()将返回一个代码,该代码指示您的C程序返回了什么或者它是否已被信号终止; 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. 您可能想使用像IPC :: Cmd这样的模块,该模块具有您可能需要的其他一些功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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