C中系统调用的Filehandle问题

C中系统调用的Filehandle问题,c,perl,unix,filehandle,file-descriptor,C,Perl,Unix,Filehandle,File Descriptor,在我的C程序中,我进行一个系统调用,执行“cat”UNIX命令,类似这样的命令 sprintf(command, "cat %s", filename); fprintf(stderr, "Executing command: '%s'\n", command); system(command); 当我编译并运行程序时,命令没有正确执行。相反,我得到了以下错误 Executing command: 'cat temp.txt' cat: stdout: Bad file descriptor

在我的C程序中,我进行一个系统调用,执行“cat”UNIX命令,类似这样的命令

sprintf(command, "cat %s", filename);
fprintf(stderr, "Executing command: '%s'\n", command);
system(command);
当我编译并运行程序时,命令没有正确执行。相反,我得到了以下错误

Executing command: 'cat temp.txt'
cat: stdout: Bad file descriptor
我的问题有两个方面

  • 为什么这段代码不能正常工作,我如何修复它
  • 当我在命令行上尝试类似于
    perl-e'system(“cat temp.txt”)
    的东西时,它可以正常工作。Perl处理文件句柄的方式与C处理文件句柄的方式有什么区别
  • 谢谢

    更新:多亏了这些评论,我很快就解决了这个问题。我之前在程序中意外地关闭了stdout,这就是
    cat
    程序试图打印到stdout时出错的原因。因此,看起来C和Perl处理文件句柄的方式没有区别:下面的命令生成完全相同的错误

    $ perl -e 'close(STDOUT); system("cat temp.txt")'
    cat: stdout: Bad file descriptor
    

    似乎默认的
    stdout
    文件描述符不存在<代码>标准输出已关闭。

    是否对标准输出执行了任何操作?可能在调用之前它已关闭?您是否已关闭标准输出?您是如何运行该程序的?您可能已经关闭了stdout(例如,如果您分叉),您是否出于某种原因关闭了
    stdout
    ?@FooBah:forking不会关闭stdout。