开发者

after fork/execvp control does not return to parent

when i run my code below and type in "ls" at the prompt it runs ls in the terminal but then just sits there and doesnt print my prompt again. How do I get control to go back to the parent process?

Thanks

#include 开发者_JAVA百科<stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[]){
    while(1){
        print_the_prompt();
        char user_text[100];
        if( fgets(user_text, sizeof(user_text), stdin) != NULL ){
            char* nl_char = strchr(user_text, '\n');
            if( nl_char != NULL ){
                *nl_char = '\0';
            }
        }

    //printf("user_text = \"%s\"\n", user_text);

        if( is_command_built_in(user_text) ){
            //run built in command
        }
        else{
            //run regular command
            execute_new_command(user_text);
        }
    }

    return 0;
}

void print_the_prompt(){
        printf("!:  ");
}

int is_command_built_in(char* command){
    return 0;
}

void execute_new_command(char* command){
    pid_t pID = fork();
    if(pID == 0){
        //is child
        char* execv_arguments[] = { command, (char*)0 };
        execvp(command, execv_arguments);
    }
    else{
        //is parent
        printf("im done");
    }
}


The answer is probably that the parent prints "im done" immediately after starting the child (remember it's a separate process and therefore runs in parallel), and then loops back around to print the prompt before the child even starts listing files. If you scroll back you'll probably find your next prompt.

To have the parent wait for the child to finish, you will have to use one of the wait() family of functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜