c - fork() 后失去控制

标签 c shell wait

我正在编写一个简单的程序来更好地理解 fork()、wait() 和 execvp()。我的问题是,运行程序后,控制权没有传递回 shell,我不知道为什么。我想要的是在代码完成后能够在 shell 中输入另一个命令。我看了一下this ,但我认为它不适用于我的情况。我基本上只是从 here 找到的复制代码.

输入/输出(# 位于我输入的行前面,但不是输入的一部分):

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

我的代码:

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;
}

最佳答案

这一行

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

不正确

你需要

wait(&status);

或者使用waitpid - 请参阅here

关于c - fork() 后失去控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15262446/

相关文章:

macos - 在登录期间为所有用户启动 cocoa 应用程序

android:警报对话框不等待输入

node.js - Nodejs Childexec 对文件中的每一行执行命令,但等待第一个命令退出,然后再运行下一个命令

c - 通过 fputc 与 C 中的 fwrite 数组写入文件

c - 在c中链接2个目标文件以创建可执行文件

c - 事件驱动与使用返回值的调用者相比

javascript - Scrapy Splash 不尊重渲染 "wait"时间

c - 如何在C中找到数字中的最小数字及其在 vector 中的位置?

linux - 用于终止具有最高 PID 的进程的 Shell 脚本

shell - 如何使用shell判断软件是否安装?