Perl 和外部程序

发布于 2024-09-12 15:20:12 字数 291 浏览 3 评论 0原文

我有一个 Perl 程序和一个 C 程序。我想运行Perl程序并捕获C程序的返回值。为了说清楚:

C 程序(a.out)

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

Perl 程序:

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

有什么想法吗? 谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

悲欢浪云 2024-09-19 15:20:12

我不了解 perl,但这适用于我的系统,所以不能保证:

#!/usr/bin/perl

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

出于某种原因,system() 返回返回值按 8 位移动(因此 0 将变为 256,1 将变为 512。 .. 7 将是 1792 或类似的东西)但我不想查为什么。

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.

九命猫 2024-09-19 15:20:12

您的 C 程序没有打印回车符,因此您可能会遇到行缓冲问题。

试试这个:

printf("100\n");

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

Try this instead:

printf("100\n");
调妓 2024-09-19 15:20:12

system() 将返回一个代码,指示您的 C 程序返回了什么或者它是否被信号终止;假设后者不是这种情况,你可以做

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

如果你也希望捕获输出,你可以使用反引号,代码将在 $?多变的。

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

您可能想要使用像 IPC::Cmd 这样的模块,它具有您可能需要的其他几个功能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文