【问题标题】:Output Redirection in C shellC shell 中的输出重定向
【发布时间】:2011-04-26 10:32:47
【问题描述】:

我在上一个问题中询问了管道,得到了完美的工作。但是,我对输出重定向有一些疑问,例如 shell 中的 >> 通常会这样做。互联网上似乎没有很多关于它的信息。这是我到目前为止所拥有的。有没有更好/更简单的方法来做到这一点,它很混乱,我什至不确定我是否理解它。其中一部分是注释中给出的伪代码,我有点填写它们,但我什至不确定。

void do_redirect(char** cmd, char** file) {
  int fds[2]; 
  int count; 
  int fd;     
  char i;    
  pid_t pid;  
  pipe(fds);
  //File Descriptors/pipe and redirecting char variables (i)
  //fd is used with the open command, basically stores the 

  //Child 1
  if (fork() == 0) {
    //Open the file with read/write commands, 0_CREAT creates the file if it does not exist
    fd = open(file[0], O_RDWR | O_CREAT, 0777);
    dup2(fds[0], 0);

    //Close STDOUT
    close(fds[1]);

    //Read from STDOUT
    while ((count = read(0, &i, 1)) > 0)
    write(fd, &i, 1); // Write to file.

    exit(0);

  //Child 2
  } else if ((pid = fork()) == 0) {
    dup2(fds[1], 1);

    //Close STDIN
    close(fds[0]);

    //Output contents to the given file.
    execvp(cmd[0], cmd);
    perror("execvp failed");

  Parent
  } else {
    waitpid(pid, NULL, 0);
    close(fds[0]);
    close(fds[1]);
  }
}

【问题讨论】:

  • 我在这里没有看到问题。确切地说,你想知道什么?
  • 我基本上是想问这个“看起来”是否正确。另外如何阅读,我使用 0 而不是实际的“fd”描述符,因为我尝试使用 fd 而不是 0(就像手册页所说的那样)并且我得到了一个没有任何内容的可执行文本文件......跨度>
  • 这是作业吗?如果是这样,请将其标记为这样。

标签: c unix shell redirect


【解决方案1】:

如果您要查找的是>>,则需要O_APPEND

【讨论】:

  • 谢谢,我添加了它,虽然......如果你没有使用 0_APPEND 和 u >> cat 到一个已经存在的文件,它只是替换它还是把它放在开头?跨度>
  • 如果你试图实现 shell,你应该为 >> 而不是为 > 添加 O_APPEND。
猜你喜欢
  • 2016-03-10
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多