C MiniShell实现

时间:2014-09-27 20:40:21

标签: c++ c linux shell unix

我想知道是否有人可以在这个MiniShell实现中验证我正确进行后台处理,如果它不正确,如果提供了一些帮助就很好。 如果提供的所有代码太多请指教,我会编辑帖子。感谢

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <signal.h>
#include "my_shell2.h"

extern char **environ;

int main (int argc, char *argv[], char *envp[]){

char input[MAX_BUFFER];
char *args[MAX_ARGS];
char tok[MAX_BUFFER];

int status;
int num_args;
pid_t pid;
int background;

signal(SIGINT, SIG_IGN);
signal(SIGINT, ctrl_C_signal);

while(1){
    pid = waitpid(-1, &status, WNOHANG);

    //Display the prompt and gather user input
    fprintf(stdout, "Mini_Shell$ ");
    if ( ( fgets(input, MAX_BUFFER, stdin) ) == NULL ) {
        fprintf(stderr, "Reading in input failed.  Try again.\n");
        continue;
    }

    //Check to see if user entered anything
    if ( ( strcmp(input, "\n") == 0 ) ) {
        fprintf(stderr, "User must enter a valid command. Try again.\n");
        continue;
    }

    //Split the input commands into individual arguments
    input[strlen(input) - 1] = '\0';
    num_args = parse_commands(input, args, tok);

    //Identify what to execute, and potentially supply arguments
    if ( ( strcmp(args[0], "exit") ) == 0 ) {
        exit(0);
    }
    else if ( ( strcmp(args[0], "mydispenv") ) == 0 ) {
        mydispenv();
    }
    else if ( ( strcmp(args[0], "mysetenv") ) == 0 ) {
        mysetenv(args[1]);
    }
    else if ( ( strcmp(args[0], "myexportenv") ) == 0 ) {
        myexportenv(args[1], envp);
    }
    else {
        //Check to determine if the last argument specifies a background process
        background = ( ( strcmp(args[num_args - 1], "&") ) == 0 );
        if (background){
            args[num_args - 1] = NULL;
            if ( ( pid = fork() ) == -1 ){
                perror("fork failed");
                exit(1);
            }
            else if (pid == 0){
                fprintf(stdout, " pid == (%d) the child will run in the background \n",   pid);
                if (execvpe( args[0], args, envp )){;
                    perror("exec failed");
                    return 1;
                }
            }

        }
        else {
            if ( ( pid = fork() ) == -1 ){
                perror("fork failed");
            }
            if (pid != 0) {
                fprintf(stdout, "Waiting on child process (%d)\n", pid);
                if ( ( waitpid(pid, &status, 0) ) == -1 ){
                    perror("wait failed");
                }
                fprintf(stdout, "Child (%d) is done\n", pid);
            }
            else {
                if ( execvpe( args[0], args, envp ) ) {
                    perror("exec failed");
                    exit(0);
                }
            }
        }
    }
}

return 0;

}

0 个答案:

没有答案