c - 使用 fork() 时出现奇怪的输出

标签 c linux process

我正在尝试创建一个基于时间的池:您要么回答所有问题,要么时间到了。我最初的逻辑是让 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);
  1. &answer 应该读作 answer
  2. 您从一开始就不会为 answer 分配内存。

这会产生 undefined behaviour ,这意味着您的程序完全有权利做任何它想做的事。 :)

(感谢 @EugeneSh. 指出缺少的符号!)

关于c - 使用 fork() 时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899669/

相关文章:

c - if (variable) { while(variable){...} } 如何在 C 编程中工作?

c - 我正在尝试有条件地扫描数据,只要它不是 C 中文件的末尾

c - 用循环填充二维数组

c - 找出套接字的传输类型

linux - 使用进程间通信 (IPC) 的性能影响

c++ - 我想获取我在 C++ 中创建的每个进程的 PID,并在特定时间后终止每个进程

python - 为什么我们应该在 subprocess.Popen 中使用 stdout=PIPE?

python - 如何在了解时间常数和稳态值的 gekko 中构建过程模拟器

linux - 如何使符号链接(symbolic link)与远程挂载一起使用?

linux - 如何检查 find 命令是否没有找到任何东西?