【问题标题】:Creating a background process for shell in c在c中为shell创建后台进程
【发布时间】:2013-12-24 07:37:22
【问题描述】:

我试图用 C 语言制作自己的 shell,但在处理后台和前台进程时遇到了麻烦。这里是我创建流程的地方:

void call_exec(char *cmd) 
{
pid_t cpid;
is_Background();
if(index(cmd, '/') == NULL) {
    int i;
printf("cmd is %s\n", cmd);
cpid = fork();
if(cpid == 0) {
    i = execvp(cmd, my_argv);
    if(i < 0) {
        printf("%s: %s\n", cmd, "command not found");
        exit(1);        
    }   
} 
else {
    if(!is_BG ) {
        wait(NULL);
    }
    is_BG = 0;
}
}

is_Background:

void is_Background() {
if(strcmp(my_argv[arg_index], "&") == 0) {
    is_BG = 1;
    my_argv[arg_index] = NULL;
}
}

当我运行我的代码并在命令行中输入“gedit”时,shell 会一直等到我关闭 gedit 窗口,然后提示我输入新命令。当我输入“gedit &”在后台运行 gedit 时,它工作正常,gedit 窗口打开,shell 立即提示我输入新命令,而无需等待关闭 gedit 窗口。问题是,在我对任何命令只使用一次“&”之后,shell 永远不会等待任何前台进程结束/关闭。例如,如果我在没有 "&" 的情况下输入 "gedit" 或 "firefox" ,shell 不会等待它们关闭。

我希望我能正确解释我的问题,我的英语不是很好,很抱歉有错误。如果我需要提供更多信息,请告诉我。谢谢。

【问题讨论】:

    标签: c linux bash shell exec


    【解决方案1】:

    这里有两个问题:

    首先,gedit 和 firefox 是单实例程序。任何其他调用只会重用现有实例。你在 bash 中看到同样的东西:

    bash$ gedit &   # Starts gedit and returns immediately
    bash$ gedit     # Opens a new tab in the existing window and returns immediately
    

    您应该使用多个实例程序进行测试,例如 xtermxeyes

    其次,您的wait(NULL) 调用等待任何进程关闭,不一定是最后一个。在你的 shell 中,你可能会看到:

    yourshell$ xterm &  # starts xterms and returns immediately. 
    # Now close the xterm before running the next command
    yourshell$ xeyes    # starts xeyes, waits on xterm, returns immediately
    

    您可以改用waitpid(cpid, NULL, 0) 来等待正确的进程。

    【讨论】:

    • 我想知道如何测试它,我首先想到的是 gedit。非常感谢您的帮助。
    • @thatotherguy waitpid(cpid, NULL, 0) 为什么status 参数是NULL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2012-09-30
    相关资源
    最近更新 更多