0

私はfork()、wait()、およびexecvp()をよりよく理解するための簡単なプログラムを書いています。私の問題は、プログラムを実行した後、制御がシェルに戻されず、その理由がわからないことです。私が欲しいのは、コードが終了した後にシェルに別のコマンドを入力できるようにすることです。これを見てみました、私の場合は当てはまらないと思います。基本的に、ここから見つけたコピーしたコードだけです。

入出力(#は入力の一部ではありませんが、入力した行の前にあります):

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

1 に答える 1

2

この行

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

間違っている

あなたが必要です

wait(&status);

または使用waitpid-ここを参照してください

于 2013-03-07T03:20:38.593 に答える