heya
got a small problem here. im trying to pipe eg: 'ls | more'.
i have created a command line parser which separates ls and more into two commands. i have also created a struct, each struct has a command name, number of arguments, redirect_in, redirect_out, pipe_in, etc etc.... eg:
struct com[0].com_name would be : ls
struct com[0].pipe_to = 1 ( 1 means pipe to command 1 )
struct com[1].com_name would be : more
now when i try and pipe the above ( ls | more ), only the 'ls' command is executed and more is not. the execute method is called from the main class eg :
for (k = 0; k < lc; k++) {
execute(cl[k], k);
}
this is my execute method:
// ----------------------------------------------------------
/*
* This function dumps the contents of the structure to stdout in a human
* readable format..
*
* Arguments :
* c - the structure to be displayed.
* count - the array position of the structure.
*
* Returns :
* None.
*
*/
void execute(command *a, int count) {
int fd[2];
int status;
int pid;
int command = 0;
// redirect out
if (a->redirect_out != NULL) {
int out;
out = open (a->redirect_out, O_TRUNC | O_CREAT | O_WRONLY, 0777);
if (out <= 0) {
fprintf (stderr, "Couldn't open a file\n");
exit (errno);
}
dup2 (out, 1);
close (out);
}
// redirect in
if (a->redirect_in != NULL) {
int in;
in = open (a->redirect_in, O_RDONLY);
if (in <= 0) {
fprintf(stderr, " \n in = %d ", in);
fprintf (stderr, "Couldn't open a file\n");
exit (errno);
}
dup2 (in, 1);
close (in);
}
// change directory
if (strncmp (a->com_name, "cd", 2) == 0){
if (!a->argv[1])
a->argv[1]=(char *)
get_userdir();
chdir (a->argv[1]);
exit(0);
}
// exit
if (strncmp (a->com_name, "exit" , 4) == 0) {
fprintf (stdout, "Quit. \n");
exit(0);
}
if (a->pipe_to == 1) {
pipe(fd);
}
pid = fork();
// create a process space
if (pid == 0) {
// child process
if (a->pipe_to == 1) {
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execvp(a->com_name, a->argv); // 'more'
_exit(0);
}
else {
execvp(a->com_name, a->argv);
}
}
else {
// parent process
if (a->background == 1) {
printf(" \nin background ");
signal(SIGCHLD, SIG_IGN); // to ignore child-termination signals
_exit(0);
}
if (a->pipe_to == 1) {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execvp(a->com_name, a->argv); 'ls'
wait(NULL);
}
// let's wait for the child to finish
else {
waitpid (pid, NULL, 0);
}
}
return;
}
what i think needs to be done is when the 'ls' command is executed, it should go back to the main program, increase 'k++' (increase command by 1) and go back to the execute method without forking again and execute the command pathname of command which was just increased-> but it doesnt seem to be doing that.
can anyone please help
appreciated, mile 1982