【问题标题】:Redirect command output to file in C将命令输出重定向到 C 中的文件
【发布时间】:2015-08-10 19:41:05
【问题描述】:

我正在尝试将 ls 命令的输出重定向到文件 fout.txt 但文件 fout.txt 仅包含 这是输出

下面是我的程序:

int fout, ferr;
char *tok[3];
tok[0] = "ls", tok[1] = ">", tok[2] = "fout.txt";
fout = open("fout.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
ferr = open("ferr.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
puts("Here is the output\n");
execvp(tok[0], tok);
close(fout);
close(ferr);

请在这里帮忙。

【问题讨论】:

  • 你在什么操作系统上运行这个?
  • 另外,您确定您使用的是puts 而不是fputsfout
  • 你不检查 execvp() 的返回值。可能由于文件 fout.txt 当前被另一个进程(您的程序)打开而失败。
  • 文件怎么可能不为空?你永远不会给它写信!但你至少应该在某处看到ls: >: No such file or directory...

标签: c


【解决方案1】:

您尝试的重定向不是直接通过execvp() 调用完成的。在bashlike this完成:

/* Execute a simple command that is hopefully defined in a disk file
   somewhere.

   1) fork ()
   2) connect pipes
   3) look up the command
   4) do redirections
   5) execve ()
   6) If the execve failed, see if the file has executable mode set.
   If so, and it isn't a directory, then execute its contents as
   a shell script.

   Note that the filename hashing stuff has to take place up here,
   in the parent.  This is probably why the Bourne style shells
   don't handle it, since that would require them to go through
   this gnarly hair, for no good reason.

注意“连接管道”。

(这并不是一个完整的答案 - 应该要求提问者研究某事...)

【讨论】:

    【解决方案2】:

    不同的重定向字符 (< > >> |) 由 shell 解释。当您要求直接执行execvp 时,您只需执行带有参数>fout.txtls 命令。

    当我这样做时,我会进入 stderr:

    ls: >: No such file or directory
    ls: fout.txt: No such file or directory
    

    要使用 exec 系列函数重定向,您必须显式打开文件并使用 dup2 将它们连接到 stdin (0)、stdout(1) 和/或 stderr(2),如 In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call? 所示

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2013-11-15
      • 1970-01-01
      • 2020-08-10
      • 2015-10-30
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多