[英]Weird behaviour on redirection of exec() output
我正在編寫一個程序,該程序創建一個txt文件input.txt
,並將其用作exec()
輸入。 我將其輸出重定向到另一個文件output.txt
遇到問題,它們似乎鏈接到input.txt
編寫。
如果我使用fwrite(array, 4, 1, file)
重定向工作。 如果我使用fwrite(array, sizeof(array), 1, file)
或fprint
,則不會。
FILE *finput = fopen("input.txt", "w");
for (int i=0; i<dimension; i++)
{
char c; // I get it from another file, it isnt't important.
char arr[1];
arr[0] = c;
// WORKING LINE OF CODE
fwrite(arr, 4, 1, finput);
// NOT-WORKING LINE OF CODE
// fwrite(arr, sizeof(arr), 1, finput);
// ANOTHER NOT-WORKING LINE OF CODE
// fprintf(finput, "%c", c);
}
pid_t pid;
int status = -1;
pid = fork();
if (pid == -1)
{
printf("ERROR.");
}
else if ( pid == 0)
{
int fdOutput = creat("output.txt", 0777);
dup2(fdOutput, 1);
dup2(fdOutput, 2);
close(fdOutput);
// awkScript is an awk program string
int executionResult = execl("/usr/bin/gawk", "gawk", awkScript, "input.txt", (char*)NULL);
// ...
}
如果編寫代碼行,則在程序末尾, output.txt
文件中將包含一些文本。 否則, 它完全是空的。
最奇怪的是, input.txt
仍然可以正常工作,始終可以正確編寫。 所以我不明白為什么要把它與寫作聯系起來。 如果我執行命令:
gawk $awkScript input.txt
以用於寫入input.txt
所有三種方式打印輸出
此代碼有多個問題(例如大小4…它來自哪里?您的數組長1個字節;因此這是未定義的行為),但是失敗的根本原因是您無法關閉文件。 這意味着輸出緩沖區永遠不會被刷新,並且不會寫入任何輸出。
fclose
文件,或至少在寫入后將其fflush
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.