首页 > 解决方案 > scanf 子进程后的垃圾值

问题描述

我的scanf声明在子进程中无法正常工作:

int main(int argc, char **argv)
{
    int operando, operatore;

    pid2 = fork();
    if (pid2 == 0) { // Figlio 2

        printf("Inserisci due numeri: ");

        scanf("%d%d", &operando, &operatore); //even though I " %d%d"...

        printf("Operando is %d and operatore is %d\n", operando, operatore);

    }


    return 0;
}

这是输出: 错误

标签: cscanfforksystem-calls

解决方案


请参阅此问题以了解程序中发生的情况:Child process cannot read after the exiting of parent process。最重要的部分:

终端由前台进程组控制。当 shell 调用父进程时,它使父进程成为前台进程组的领导者。孩子继承该组并有权访问终端。

但是,当父进程退出时,shell 会收回对终端的控制权并成为前台进程组的领导者。子进程不再在前台进程组中,因此无法访问终端。

要让您的程序按预期工作,wait请在父进程中添加一个调用,以确保父进程在子进程完成之前不会退出,从而使终端对子进程可用。

例如:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char **argv)
{
    int operando, operatore;

    pid_t pid2 = fork();

    if (pid2 == 0) { // Figlio 2
        printf("Inserisci due numeri: ");    
        scanf("%d%d", &operando, &operatore); //even though I " %d%d"...    
        printf("Operando is %d and operatore is %d\n", operando, operatore);
    } else if (pid2 > 0) {
        wait(NULL);
    }
    
    return 0;
}

请注意,需要考虑的其他一些一般性改进:

  • 始终检查函数调用的返回值。scanf尤其应在使用前检查结果printf。同样,fork应检查返回值是否有错误。

推荐阅读