OK, here goes.
I have to write a program, in which I need to use strtok and dup2 to redirect one file to another, but I need to also have the user to actually put the command cat < file1 file2, but not from the shell, but instead by using my program. That's why I need strtok. And the reason my program doesn't work is probably because of that, because I don't really understand how strtok works. I found a similar program on the internet, but they just take the ls command and redirect it to the file. That's it. My program is much more complicated. I mean, it would've been easier just to say in shell cat < file1 file2, but for some reason they want us to do it this way.
So, anyways, here is what I have so far (here I just combined what I have found on the internet with what I already had from before. We had to do something similar but then the user would just go ls or ls -l. Very simple stuff. This is much harder, for me, at least.)
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
int main() {
pid_t pid;
char line[256];
char *args[129];
int i;
int fd;
int status;
char *temp;
while (1) {
printf(">");
if (fgets(line, 256, stdin) == 0) {
exit(0);
}
else {
pid = fork();
if (pid == 0) {
i = 0;
temp = strtok("<",line);
while (temp != NULL) {
args[i++] = temp;
temp = strtok(">",line);
args[i] = '\0';
}
fd = open("hello", O_RDONLY);
dup2(fd, STDIN_FILENO);
fd = open("world", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
dup2(fd, STDOUT_FILENO );
close(fd);
execvp(args[0], args);
}
else {
close(fd);
wait(&status);
}
}
}
}
Any help would be greatly appreciated.