Search code examples
cshellwaitpidsigaction

Minishell background


I am doing a minishell project for college, and I don't know how to execute commands in background. The one thing i know is that i have to use waitpid() and sigaction(), but i don't know how. If somebody would give me a hand with this i will be gratefull. Here is the part of the code that I use, to make use of the minishell commands.

void execute_command_line(command* cmds, int n){
        pid_t id,pid;
        int status;
        id=fork();
        if(id==-1){
            exit(EXIT_FAILURE);
        }
        else if(if==0){
                 execvp(cmds[0] . argv[0],&cmds[0] .argv[0]);
                 exit(0);
        }
        else{
             pid=wait(&status);
             if(pid==-1){
                perror("Father: an error has ocurred.\n");
                exit(EXIT_FAILURE);
             }
             else if(pid==id){
                     printf("Father: the son has ended.\n");
            }
     }

}


Solution

  • A key characteristic of a background process is that you can't interact with it (but it can still print to your terminal). This means, at minimum, that the keyboard-generated signals must not be delivered to that process. This can be accomplished by creating a new session by calling setsid(), or it can be simulated by simply disabling the keyboard signals in the child (there is your sigaction).

    Using waitpid implies that your parent may not exit right away, but rather it will wait (using waitpid) for the background child to finish.

    So... Replace the wait with waitpid() and disable the keyboard interrupts (SIGINT and SIGQUIT) with sigaction() and you'll have your background execution.