【问题标题】:after fork/execvp control does not return to parent在 fork/execvp 控制不返回父级之后
【发布时间】:2011-09-28 02:13:05
【问题描述】:

当我在下面运行我的代码并在提示符处键入“ls”时,它会在终端中运行 ls,但然后就坐在那里并且不再打印我的提示符。如何获得控制权以返回父进程?

谢谢

#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");
    }
}

【问题讨论】:

    标签: c process exec fork execvp


    【解决方案1】:

    答案可能是父进程在启动子进程后立即打印“im done”(记住这是一个单独的进程,因此并行运行),然后循环返回以打印之前的提示孩子甚至开始列出文件。如果您向后滚动,您可能会找到下一个提示。

    要让父级等待子级完成,您必须使用wait() 系列函数之一。

    【讨论】:

    • 哦哦好的。我不知道等待()。我会调查一下。你是对的,它在打印来自 ls 的内容之前打印了“我完成了”。
    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2013-02-24
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多