c - Redirecting one file to another using dup2 and strtok -
i have write program, in need use strtok , dup2 redirect 1 file another, need have user put command cat < file1 > file2, not shell, instead using program. that's why need strtok. , reason program doesn't work because of that, because don't understand how strtok works. found similar program on internet, take ls command , redirect file. that's it. program more complicated. mean, would've been easier in shell cat < file1 > file2, reason want way. so, anyways, here have far (here combined have found on internet had before. had similar user go ls or ls -l. simple stuff. harder, me, @ 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) { = 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 appreciated.
besides backwards strtok
arguments, there other problems.
- the parent process closes
fd
never opened (it's uninitialized variable there, you're closing random fd may not exist) - the child process 2 opens , 2 dup2's 1 close. you're leaking fd.
- hardcoded filenames
- you single "<" have loop detecting multiple ">"s
- lack of
<stdlib.h>
exit()
- who thinks
s_irwxu
more readable0700
?
and if you're aiming approximate behavior of real shell, should @ least ignore whitespace around redirection operators.
Comments
Post a Comment