dup2 没有切换到文件?

dup2 not switching to file?

我正在尝试学习 dup2 并将标准输出切换到文件而不是终端。这是在任何地方都适用的示例,但不确定为什么它对我不起作用。我不认为我需要 fork() 因为我不需要不同的过程来执行文件中的打印语句。

调用函数的地方:

int main(int argc, char **argv){
  char *something = "hello";
  saveHistoryToFile(something);
}

//这个是函数。有一个文件名 history .txt

void saveHistoryToFile(char *history){
  int fw = open("history.txt",O_WRONLY | O_APPEND);
  dup2(fw, 1);
  printf("%s", history);
}

错误:它打印到终端而不是文件!

你的错误检查代码:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int saveHistoryToFile(char *history);

int main(int argc, char **argv){
  char *something = "hello";
  if(0>saveHistoryToFile(something)) return 1;
  if(0>fclose(stdout)) return perror("fclose"),-1;
}

int saveHistoryToFile(char *history){
  int fw = open("history.txt",O_WRONLY | O_APPEND /*|O_CREAT, 0640*/ );
  if (0>fw) return perror("open"),-1;
  if (0>dup2(fw, 1)) return perror("dup2"),-1;
  if (0>(printf("%s", history)))  return perror("printf"),-1;
}

在第一个 运行 上,我得到 "open: No such file or directory",因为我的当前目录中没有 "history.txt"

如果我添加它或取消注释 O_CREAT, 0640,它 运行 在我的机器上没问题。

当然,您可能 运行 遇到其他问题(例如 EPERM),但是 perror 应该会给您提示。