简体   繁体   English

C语言系统调用的文件句柄问题

[英]Filehandle issue with system call in C

In my C program I make a system call that executes the 'cat' UNIX command, something like this. 在我的C程序中,我进行了一个系统调用,执行'cat'UNIX命令,就像这样。

sprintf(command, "cat %s", filename);
fprintf(stderr, "Executing command: '%s'\n", command);
system(command);

When I compile and run the program, the command is not executed properly. 编译并运行程序时,命令未正确执行。 instead I get the following error. 相反,我得到以下错误。

Executing command: 'cat temp.txt'
cat: stdout: Bad file descriptor

My question is two-fold. 我的问题是双重的。

  1. Why is this code not working correctly, and how can I fix it? 为什么此代码无法正常工作,我该如何解决?
  2. When I try something like perl -e 'system("cat temp.txt")' on the command line, it works as expected. 当我在命令行上尝试像perl -e 'system("cat temp.txt")'这样的东西时,它按预期工作。 What is the difference between how Perl deals with file handles and how C deals with them? Perl如何处理文件句柄和C如何处理它们之间有什么区别?

Thanks! 谢谢!

Update : Thanks to the comments, I figured out the problem pretty quickly. 更新 :感谢评论,我很快发现了问题。 I had accidentally closed stdout earlier in the program, which is why there was an error when the cat program tried to print to stdout. 我在程序的早期意外关闭了stdout,这就是为什么当cat程序试图打印到stdout时出错。 So it looks like there is no difference between how C and Perl deal with file handles: the following command generates the exact same error. 因此看起来C和Perl如何处理文件句柄之间没有区别:以下命令生成完全相同的错误。

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

Seems like your default stdout file descriptor is not there. 好像你的默认stdout文件描述符不存在。 stdout is closed. stdout已关闭。

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

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