【问题标题】:Junk values after scanf child processscanf 子进程后的垃圾值
【发布时间】:2023-08-08 02:58:01
【问题描述】:

我的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;
}

这是输出: error

  • 如何解决?

【问题讨论】:

  • return 0;之前添加wait(NULL);调用到父进程。
  • 这里是需要wait 的原因:*.com/questions/21793755/…
  • 另外 - 总是检查输入函数的返回值,例如scanf()
  • 根据“错误”链接,您没有输入两个预期的整数值,因此对 scanf() 的调用失败

标签: c scanf fork system-calls


【解决方案1】:

scanf() 的调用失败。如果代码检查了scanf() 的返回值,则该代码可能知道这一点。任何返回值不是 2 都表示发生了错误。

scan() 在第一个“输入格式转换”说明符上失败,因此它从未查看第二个“输入格式转换”说明符。

当调用 scanf() 中的整数“输入格式转换”说明符失败时,目标变量设置为 0。第二个变量显示内存中堆栈位置的垃圾。

【讨论】:

    【解决方案2】:

    请参阅此问题以了解您的程序中发生的情况: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;
    }
    

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

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

    【讨论】:

    • 仅供参考,我没有直接重复引用的问题,因为它解释了问题是什么,但没有提供该问题的具体解决方案。