C中系統調用的文件句柄問題 (Filehandle issue with system call in C)


問題描述

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.

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. What is the difference between how Perl deals with file handles and how C deals with them?

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. 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.

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

‑‑‑‑‑

參考解法

方法 1:

Seems like your default stdout file descriptor is not there. stdout is closed.

(by Daniel StandageAndrejs Cainikovs)

參考文件

  1. Filehandle issue with system call in C (CC BY‑SA 3.0/4.0)

#perl #file-descriptor #filehandle #unix #C






相關問題

保持特定位數的簡單 Perl 數學 (simple Perl math while keeping a specific number of digits)

如何在 Windows 批處理腳本或 Perl 中將文件移動到回收站? (How can I move files to the Recycle Bin in a Windows batch script or Perl?)

從子程序返回數組 (Return array from subroutine)

我可以以與操作系統無關的方式限制 Perl 進程使用的內存嗎? (Can I Iimit the memory used by a Perl process in an OS-agnostic way?)

$# 在 perl 中接受什麼作為輸入? (what does $# accept as input in perl?)

Perl Text::CSV_XS 從字符串中讀取 (Perl Text::CSV_XS read from string)

使用 excel 2010 更新批處理文件中的變量 (use excel 2010 to update variables in batch file)

在 perl 中為哈希添加值 (Adding value to an hash in perl)

為什麼 perl 會忽略我的正則表達式中的多餘字符? (Why does perl ignore extra characters in my regex?)

boost::regex - \bb? (boost::regex - \bb?)

如果小於 X 天,如何從磁盤讀取文件,如果舊,則重新獲取 html 文件 (How to read a file from the disk if less than X days old, if older, refetch the html file)

使用 Devel-Cover 獲取覆蓋率報告 (Using Devel-Cover to get coverage reports)







留言討論