Losing control after fork()

2019-09-07 04:19发布

问题:

I'm writing a simple program to better understand fork(), wait(), and execvp(). My problem is that after I run the program, control is not passed back to the shell and I have no clue why. What I want is to be able to input another command into the shell after the code is finished. I took a look at this, but I don't think it's applicable in my case. I've basically just the copied code I found from here.

input/output (# is in front of lines I typed, though is not part of the input):

shell> # gcc test.c -o test
shell> # ./test
input program (ls)
# ls
input arg (.)
# .
test test.c extra.txt
# a;dlghasdf
# go back
# :(

my code:

int main(void) {
    //just taking and cleaning input
    printf("input program (ls)\n");
    char inputprogram [5] = {0,0,0,0,0};
    fgets(inputprogram,5,stdin); //read in user command
    int i;
    for(i = 0; i < 5; i++) {
        if(inputprogram [i] == '\n' ){
            inputprogram[i] = 0;
        }
    }

    printf("input arg (.)\n");
    char inputarg [5] = {0,0,0,0,0};
    fgets(inputarg,5,stdin); //read in user command
    for(i = 0; i < 5; i++) {
        if(inputarg [i] == '\n' ){
            inputarg[i] = 0;
        }
    }

    char per []= {inputarg[0], 0};
    char *arg [] = {inputprogram, per , NULL};

    int status = 0;
    pid_t child;

    //the fork(), execvp(), wait()
    //////////////////////////////////
    if ((child = fork()) < 0) {
        /* fork a child process           */
        printf("*** ERROR: forking child process failed\n");
        exit(1);
    } else if(child == 0){
        execvp(inputprogram, arg);
        exit(1);
    } else {
        while(wait(&status != child));
    }

    return EXIT_SUCCESS;
}

回答1:

This line

while(wait(&status != child));

is incorrect

You need

wait(&status);

Or use waitpid - See here



标签: c shell wait