【问题标题】:why execl overwrite the file为什么execl会覆盖文件
【发布时间】:2015-02-23 00:23:22
【问题描述】:
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h> // open
#include <stdio.h>

int main() {
  close(1); // close standard out
  open("log.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  puts("Captain's log");
  chdir("/usr/include");
  execl("/bin/ls", "ls", ".", (char *)NULL); 
  perror("exec failed");
  return 0;
}

当我检查 log.txt 时,我找不到“船长的日志”。我认为它在 execl 之前运行,因此它应该在那里!

【问题讨论】:

  • 试试fflush(stdout);
  • @kww 问题解决了吗?
  • @immibis 当我添加 'fflush(stdout);'在 'puts("Captain's log");' 之后,它起作用了。谢谢!

标签: c execl


【解决方案1】:

您正在将其写入标准输出,为什么希望它在文件中?

如果你想重定向stdout,只需使用freopen()

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <unistd.h>

int main()
{
    FILE *file;

    file = freopen("log.txt", "w", stdout);
    if (file == NULL)
        return -1;

    printf("Captain's log");
    chdir("/usr/include");

    if (execl("/bin/ls", "ls", ".", NULL) != 0)
        perror("exec failed");
    fclose(file);

    return 0;
}

【讨论】:

  • 您好,我运行了您的代码,但仍然无法在 log.txt 中找到“Capitain log”。你运行你的代码了吗?当我关闭支架输出时,我认为它应该转到 log.txt。这也是 execl 的输出所在。我想知道它是否不像我想象的那样工作。
  • 我认为@immibis 是对的。如果您添加 'fflush(stdout);',您的代码也可以工作在'printf("船长日志");'之后
  • @kww 所以只是printf("Captain's log\n")?我的代码因为fclose() 而工作,因为fclose() 也会刷新缓冲区。
  • 我测试了你的代码,如果你不添加'fflush(stdout);',它就不起作用在'printf("船长日志");'之后
  • @kww 它在我的情况下有效,为什么会......???我以为fclose() 会刷新缓冲区。
猜你喜欢
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 2020-10-22
  • 2016-09-16
  • 2014-04-28
  • 2017-05-08
相关资源
最近更新 更多