第二次迭代后,Scanf 无法在循环中使用 fork

Scanf doesn't work with fork in a loop after the second iteration

我不明白为什么scanf不会在循环中等待第二次输入。它只在第一次迭代中有效。还有一点 wait(&Status) 不会打印正确的 Status。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[5];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");     
        scanf("%d", &x);

        int child = fork();
        if (child != 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", Status);
        }
    }
}

就像上面的评论所说,这里有两个问题:

  1. 您是 运行 parent 中的命令,而不是 child 中的命令。参见 fork manual.

  2. 等待不会给你 return 代码。它给你一个你需要解码的整数。参见 wait manual.

这是更正后的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[6];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");
        scanf("%d", &x);

        int child = fork();
        if (child == 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", WEXITSTATUS(Status));
        }
    }
    return 0;
}