Reputation: 119
I am wondering if anyone could point me in the right direction on how to do this? For example, if I write "ls > contents.txt", I want the output of ls to be written into content.txt.
This is what I have so far.
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <ctype.h>
void parse(char *line, char **argv)
{
while (*line != '\0') {
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0';
*argv++ = line;
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++;
}
*argv = '\0';
}
void execute(char **argv)
{
pid_t pid;
int status;
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) {
if (execvp(*argv, argv) < 0) {
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else {
while (wait(&status) != pid)
;
}
}
void main(char *envp[])
{
char line[1024];
char *argv[64];
while (1){
printf("shell>>");
gets(line);
printf("\n");
parse(line, argv);
if (strcmp(argv[0], "exit")==0)
exit(0);
execute(argv);
}
}
Upvotes: 0
Views: 1357
Reputation: 975
In between test for pid==0 and before you run execvp(), you want code like this:
int fd=open(outputfile,O_WRONLY|O_CREAT);
dup2(fd,1);
This will essentially set the stdout for the program run by execvp() to be to this new file. You will have to modify your parsing code to look for the ">" and parse what comes after it as a filename and store in outputfile. You'd also want to do some additional checking to make sure the new file opens OK, etc.
Upvotes: 1
Reputation: 25119
You will need to:
> [filename]
in the command passeddup2
to attach the fd you get to the stdout
of the forked process.That should be enough to point you in the right direction.
Upvotes: 1