C shell中的输出重定向
我在前面的一个问题中问到了管道的问题,它工作得很好。然而,我对输出重定向有一些疑问,比如shell中的>>通常会这样做。互联网上似乎没有太多关于它的信息。这是我到目前为止所拥有的。有没有更好/更简单的方法可以做到这一点,它很混乱,我甚至不能肯定我是否理解它。它的一部分是在笔记中给出的伪代码,我有点填写了它们,但即使我也不太确定C shell中的输出重定向,c,unix,shell,redirect,C,Unix,Shell,Redirect,我在前面的一个问题中问到了管道的问题,它工作得很好。然而,我对输出重定向有一些疑问,比如shell中的>>通常会这样做。互联网上似乎没有太多关于它的信息。这是我到目前为止所拥有的。有没有更好/更简单的方法可以做到这一点,它很混乱,我甚至不能肯定我是否理解它。它的一部分是在笔记中给出的伪代码,我有点填写了它们,但即使我也不太确定 void do_redirect(char** cmd, char** file) { int fds[2]; int count; int fd;
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\u APPEND
。这里没有问题。你到底想知道什么?我基本上是想问这个“看起来”正确吗。还有,为什么我用0来代替实际的“fd”描述符,因为我试着用fd来代替0(就像手册上说的那样),我得到了一个没有任何内容的可执行文本文件……这是家庭作业吗?如果是这样,请将其标记为这样。谢谢,我添加了它,但是…如果您没有对已经存在的文件使用0_APPEND和u>>cat,它只是替换它还是将它放在开头?如果您试图实现shell,您应该为>>而不是>添加O_APPEND。