I asked about pipes in a previous question, got that working perfectly. However I had some questions about output redirection like >> in a shell normally does. There doesn't seem to be a whole lot of info on the Internet about it. Here is what I have so far. Is there a better/easier way to do this, it's messy and im not even super sure that I understand it. Part of it was psuedocode given in notes, i kinda filled them in, but even im not super sure.
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]);
}
}