【发布时间】:2011-10-03 12:58:30
【问题描述】:
这里可能有很多关于相同问题的问题,但目前没有一个对我有用。
我有一个 C 程序如下:
#include <stdio.h>
#include <sys/stat.h>
long size(FILE *st_in) {
struct stat st;
if (fstat(fileno(st_in), &st) == 0)
return st.st_size;
return -1;
}
int main (){
FILE *file = stdin;
long s1, s2;
s1 = size(file);
printf("Size is %ld\n", s1);
fprintf(stderr, "%d", 1);
return 0;
}
我将它编译为输出 a.out。
我有一个 xml 文件“sample.xml”
<sample>
<tag>Hello</tag>
<tag>Cool</tag>
</sample>
然后我有这个 perl 代码
#!/usr/bin/perl
use warnings;
use IPC::Open2;
open FILE, "sample.xml" or die $!;
my @xmlfile = <FILE>;
my $pid = open2(*Reader, *Writer, "./a.out");
print Writer "@xmlfile";
waitpid($pid, 0);
my @got = <Reader>;
close Writer;
close Reader;
close $pid;
print "Output got is\n";
print @got;
如果我运行通过标准输入传递 simple.xml 的 C 程序,我会得到以下信息:
[bharath@xml 18:22:34]$ ./a.out < sample.xml
Size is 60
当我运行 perl 代码时,我希望大小为 60。但我得到的是 0。
[bharath@xml 18:22:42]$ ./firmware.pl
Output got is
Size is 0
那么我该如何解决呢?我需要从 perl 中的 @array 传递 sample.xml。来自 C 程序的 stderr 整数应该存储在一个单独的变量中,而来自 C 程序的 stdout 应该存储在 perl 中的另一个单独的变量中。我认为这可能需要使用 open3 但我不知道如何使用。任何工作示例都将受到高度赞赏。
【问题讨论】:
-
在
waitpid之前关闭Writer是否有帮助?这在这里似乎有所帮助,尽管我无法精确复制(也没有尝试太精确)。