简体   繁体   中英

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

I don't understand why scanf won't wait for input the second time in the loop. it only works in the first iteration. Also somewhat wait(&Status) won't print the correct 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);
        }
    }
}

Like the comment posted above says, there are two problems here:

  1. You're running the command in the parent, rather than the child. See the fork manual .

  2. wait does not give you the return code. It gives you an integer that you need to decode. See the wait manual .

Here's the corrected code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM