我正在尝试创建一个基于时间的池:您要么回答所有问题,要么时间到了。我最初的逻辑是让 child 数数,让家长提问,但我没能实现。因此,我决定创建 2 个 child ,让 parent 协调他们的行为。
第一个 child 数时间,第二个 child 提问。它似乎在工作,除了在程序结束时,剩余的问题也会被打印出来,这有点奇怪。我的猜测是 scanf 仍在等待我按下某个键,然后它用垃圾淹没了控制台。
现在,对于一些代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int askQuestions(char* array[], int size){
char* answer;
for(int i =0 ; i < size ; i ++){
printf("%s\n",array[i]);
scanf("%s",&answer);
}
return 0;
}
int count(int bound){
int index = 0;
printf("Counting started....\n");
while(index < bound){
sleep(1);
index++;
printf("%d seconds left \n", bound-index);
}
printf("Time's up!\n");
return 0;
}
int main(){
char* questions[] = {"Q1","Q2","Q3"};
int size = sizeof(questions)/sizeof(questions[0]);
int countingTime = 3;
int status;
pid_t id1,id2;
id1 = fork();
if(id1 < 0){
printf("Fork failed");
}else{
if(id1 == 0){
status = count(countingTime);
exit(status);
}else{
id2 = fork();
if(id2 == 0){
status = askQuestions(questions,size);
exit(status);
}
}
wait(0);
}
return 0;
}
输出看起来像这样:
Counting started....
Q1
2 seconds left
1 seconds left
0 seconds left
Time's up!
[modan@HP15-ManjaroCinnamon Test]$ Q2
Q3
附言这些过程肯定会停止。 (通过顶部检查) 提前致谢。
最佳答案
scanf()
有两个问题:
char* answer;
...
scanf("%s",&answer);
&answer
应该读作answer
。- 您从一开始就不会为
answer
分配内存。
这会产生 undefined behaviour ,这意味着您的程序完全有权利做任何它想做的事。 :)
(感谢 @EugeneSh.
指出缺少的符号!)
关于c - 使用 fork() 时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899669/