简体   繁体   English

在fork / execvp控件不返回到父级之后

[英]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. 当我在下面运行我的代码并在提示符下键入“ ls”时,它将在终端中运行ls,但随后只能坐在那儿,不再打印我的提示符。 How do I get control to go back to the parent process? 如何获得控制权以返回上级流程?

Thanks 谢谢

#include <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. 答案可能是父级在启动子级后立即打印“ im done”(记住这是一个单独的过程,因此是并行运行的),然后在子级甚至开始列出文件之前回绕以打印提示。 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. 要让父级等待子项完成,您将必须使用wait()系列函数之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM