[英]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);
}
}
}
就像上面發表的評論所說,這里有兩個問題:
這是更正的代碼:
#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.