在c程序中,如何使用Linux tee重定向自身的输出[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我不能在C程序执行时使用Linux命令tee,因为我无法找到运行该程序的大项目中的哪一行代码。我正在努力想出一种方法来调用C程序中的tee命令,将其printf语句重定向到日志文件中。问题是我不能在没有像“./exe | tee some.log”这样的可执行文件的情况下调用tee,因为程序已经执行了。我做了一些研究如何获得正在运行的进程的stdout,并看到一些建议检查/ proc // fd / 1的答案。但是我不知道为什么“1”(stdout)文件是空的,我期待文件应该存储进程的printf输出。

真诚感谢任何帮助!

c linux tee
1个回答
2
投票

在调用程序之前,shell使用pipedup2设置管道。之后没有理由你不能这样做:

void pipeto(char** cmd) {
  int fds[2];
  pipe(fds);
  if(fork()) {
    // Set up stdout as the write end of the pipe
    dup2(fds[1], 1);
    close(fds[0]);
    close(fds[1]);
  } else {
    // Double fork to not be a direct child
    if(fork()) exit(0);
    // Set up stdin as the read end of the pipe, and run tee
    dup2(fds[0], 0);
    close(fds[0]);
    close(fds[1]);
    execvp(cmd[0], cmd);
  }
}

int main() {
  char* cmd[] = { "tee", "myfile.txt", NULL };
  pipeto(cmd);
  printf("This is a test\n");
}

结果:

$ ./foo
This is a test

$ cat myfile.txt
This is a test

请注意,由于shell不再知道有一个tee被管道传输,它不会等待它。这意味着如果程序退出并且shell在tee完成写入之前重绘了提示,则输出可能会有点混乱。像这样的输出纯粹是一个美容问题:

user@host $ ./foo
user@host $ This is a test

这并不意味着命令挂起,提示仍然有效,您可以键入命令或只需按Enter键重绘。

© www.soinside.com 2019 - 2024. All rights reserved.