implementing a shell in C

im currently implementing a shell in C. My problem arises when i try to run a command like this:

SHELL$: sort < txtFile | grep key

im running sort < txtFile in a process (child), and in the parent ie else if(pid > 0) im running the other command to the right of the pipe.

The program runs fine, but it exits the infinite loop that i set up in main to keep receiving input from the user.

How could i solve this problem?

this is the code i have so far to deal with the pipe, i didnt include the code that i have to deal with the redirects:

c2p is the pipe i setup for this.

if(pid == 0)
{
  if( PIPE_FLAG )
    {   
        close(c2p[0]);
        if(dup2(c2p[1], STDOUT_FILENO) == -1){
            perror("dup2() failed");
            exit(2);
        }
    }

    /* Execute command */
    execvp(cmd_args[0], cmd_args);
    perror("exec failed 1. ");          /* return only when exec fails */
    exit(-1);

} 
else if(pid > 0)
{
  if(PIPE_FLAG)
    {
        close(c2p[1]);
        if(dup2(c2p[0], STDIN_FILENO) == -1){
            perror("dup2() failed");
            exit(-1);
        }
        execvp(nxt_args[0], nxt_args);
        perror("exec failed 2. ");          
        exit(-1);    
    }
}
else 
{ 
    /* error occurred */
    perror("fork failed");
    exit(1);
}

I'm running sort < txtFile in the child process, and in the parent I'm running the command to the right of the pipe.

What happens to your shell process, then? The parent process is the shell. By running the right-side command in the parent process you're having it take over the shell's process. Remember that exec() replaces the current process.

You'll need to fork() twice, and execute the two sides of the pipe in the child processes. The parent must remain the shell, which will then wait() for the children to exit before presenting the next command prompt.


/*  How shell works */
#include<stdio.h>

#include<unistd.h>

main (int argc, char **argv)
{

  if (argc < 2)
    {

      fprintf (stderr, "nUsage: ./a.out cmd [options]...n");

    }

  if (!fork ())
    {

      argv++;

      execvp (argv[0], argv);

    }

}
链接地址: http://www.djcxy.com/p/75570.html

上一篇: 如何从我们创建的密钥库中检索我的公钥和私钥

下一篇: 在C中实现一个shell