今天想到一个问题:如果我在代码里面,fork当前进程,然后两个进程都执行scanf(),那会发生什么?键盘输入的数据是定向到哪个进程呢?

于是简单写了一段代码进行测试:

#include<stdio.h>
#include<unistd.h>

void child_process(){
    while(1){
        char c;
        scanf("%c\n", &c);
        printf("child process: %c\n", c);
    }

}
int main()
{
    printf("running...\n");

    int child_pid = fork();
    if (child_pid == 0)
        child_process();
    else
    {
        printf("parent process, child=%d\n", child_pid);
        while (1)
        {
            char c;
            scanf("%c\n", &c);
            printf("parent process: %c\n", c);
        }
    }
}

根据上面这串代码,父进程和子进程都会调用scanf,并打印自己读取到的数据。运行之后,当我在控制台输入字符,输出如下:

running...
parent process, child=33781

2
parent process: 2
parent process: 

3
child process: 3
child process: 

4
parent process: 4
parent process: 

5
parent process: 5
parent process: 

2
child process: 2
child process: 

3
parent process: 3
parent process: 

4
child process: 4
child process: 

5
parent process: 5
parent process: 

6
child process: 6
child process: 

可以看到,父进程和子进程都读取了键盘的数据。具体是哪一个进程获取到数据,则与进程调度有关。这提醒了我一点:多个进程同时读取同一个stdin的话,会造成获取到的数据不完整的问题。(这与stdin默认为tty这样的字节设备的特性有关)

转载请注明来源:https://longjin666.cn/?p=1715

欢迎关注我的公众号“灯珑”,让我们一起了解更多的事物~

你也可能喜欢

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注