簡體   English   中英

在第二次迭代后,Scanf不能在循環中使用fork

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

我不明白為什么scanf不會在循環中第二次等待輸入。 它僅在第一次迭代中有效。 另外,稍等(&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. 您在父級而不是子級中運行命令。 請參閱貨叉手冊

  2. 等待不會給您返回代碼。 它為您提供了一個需要解碼的整數。 請參閱等待手冊

這是更正的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM