简体   繁体   English

重定向exec()输出的奇怪行为

[英]Weird behaviour on redirection of exec() output

I am writing a program which creates a txt files input.txt and it uses it as input of exec() . 我正在编写一个程序,该程序创建一个txt文件input.txt ,并将其用作exec()输入。 I have problems redirecting its output to another file output.txt and they seems to be linked to input.txt writing. 我将其输出重定向到另一个文件output.txt遇到问题,它们似乎链接到input.txt编写。

If I use fwrite(array, 4, 1, file) the redirection works. 如果我使用fwrite(array, 4, 1, file)重定向工作。 If I use fwrite(array, sizeof(array), 1, file) or fprint , it doesn't. 如果我使用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);
    // ...
}

If I write the working line of code, at the end of the program I have some text in the output.txt file. 如果编写代码行,则在程序末尾, output.txt文件中将包含一些文本。 Otherwise, it is completely empty. 否则, 它完全是空的。

The weirdest thing is that input.txt works anyway, it is always correctly written. 最奇怪的是, input.txt仍然可以正常工作,始终可以正确编写。 So I can't understand why it should be connected to its writing. 所以我不明白为什么要把它与写作联系起来。 If I execute the command: 如果我执行命令:

gawk $awkScript input.txt

The output is printed in all the three ways used to write input.txt 以用于写入input.txt所有三种方式打印输出

There are multiple issues with this code (such as the size 4 … where does this come from? Your array is 1 byte long; so this is undefined behaviour) but the fundamental reason why it fails is that you fail to close your file. 此代码有多个问题(例如大小4…它来自哪里?您的数组长1个字节;因此这是未定义的行为),但是失败的根本原因是您无法关闭文件。 This means the output buffer never gets flushed, and no output written. 这意味着输出缓冲区永远不会被刷新,并且不会写入任何输出。

Either fclose the file, or at least fflush it after the write. fclose文件,或至少在写入后将其fflush

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

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