implementing a shell in C

淺唱寂寞╮ 提交于 2019-12-08 17:40:16

问题


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 i.e 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);
}

回答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.




回答2:


/*  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);

    }

}


来源:https://stackoverflow.com/questions/19941614/implementing-a-shell-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!