[英]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. 我不明白为什么scanf不会在循环中第二次等待输入。 it only works in the first iteration.
它仅在第一次迭代中有效。 Also somewhat wait(&Status) won't print the correct 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);
}
}
}
Like the comment posted above says, there are two problems here: 就像上面发表的评论所说,这里有两个问题:
You're running the command in the parent, rather than the child. 您在父级而不是子级中运行命令。 See the fork manual .
请参阅货叉手册 。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.