v_wall78
asked on
Close stdin and stdout to use redirection with a unix shell
I am creating my own shell to work as a unix shell (bash or other). I have gotten it to work with things like ls and pwd using execvp(), but I also want to be able to handle redirection like ls > out.txt. I think that I have to first close stdout and open out.txt before i call fork, but using this code:
if (!strcmp(command[i], ">"))
close(STDOUT);
I get error: STDOUT' undeclared (first use in this function).
I also tried stdout, but got the same error. Am I missing a header?
Hope someone can help me
Thanks
if (!strcmp(command[i], ">"))
close(STDOUT);
I get error: STDOUT' undeclared (first use in this function).
I also tried stdout, but got the same error. Am I missing a header?
Hope someone can help me
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In my experience, shells don't usually touch FILE * i/o, and stay in the realm of file descriptors. The idea behind freopen() can be implemented by using open() and dup2().
ASKER
I figured out how to do it:
if (!strcmp(command[i], ">")) { // if input redirection
if ((in = open(command[i+1], O_RDONLY)) == -1) { // open input file specified
fprintf(stderr, "Input file specified could not be opened.\n");
return -1; }
dup2 (in, fileno(stdin)); } // change fileid 0 from stdin to the file specified by user
if (!strcmp(command[i], ">")) { // if output redirection
if ((out = open(command[i+1], O_WRONLY|O_CREAT,0644)) == -1) { // open or create output file specified
fprintf(stderr, "Output file specified could not be opened.\n");
return -1; }
dup2 (out, fileno(stdout)); }
Thanks guys
if (!strcmp(command[i], ">")) { // if input redirection
if ((in = open(command[i+1], O_RDONLY)) == -1) { // open input file specified
fprintf(stderr, "Input file specified could not be opened.\n");
return -1; }
dup2 (in, fileno(stdin)); } // change fileid 0 from stdin to the file specified by user
if (!strcmp(command[i], ">")) { // if output redirection
if ((out = open(command[i+1], O_WRONLY|O_CREAT,0644)) == -1) { // open or create output file specified
fprintf(stderr, "Output file specified could not be opened.\n");
return -1; }
dup2 (out, fileno(stdout)); }
Thanks guys
/* Reassign "stdout" to "out.txt": */
stream = freopen( "out.txt", "w", stdout );