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