c - C shell 中的输出重定向

标签 c unix shell redirect

我在上一个问题中询问过管道,它工作得很好。但是我有一些关于输出重定向的问题,比如在 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]);
  }
}

最佳答案

如果它是您正在寻找的 >>,您将需要 O_APPEND

关于c - C shell 中的输出重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3950894/

相关文章:

linux - 在linux中访问awk外部的变量

c - 如何组合循环或如何将多个循环实现到 glib 主循环中?

c++ - 在没有条件的情况下将一个 unsigned char 的一位设置为另一个 unsigned char 的另一位

c - 链接器错误 : undefined reference to `user_input'

java - 在java中的特定目录中运行shell命令

python - 在 Python 中使用 subprocess.call ('dir' , shell=True) 时找不到指定的文件

c++ - 我可以将纯文件链接到我的可执行文件中吗?

c++ - 使用输出重定向打印到命令行

loops - zsh sleep 辅助循环

PHP strtotime 行为