scanf子进程后的垃圾值

scanf子进程后的垃圾值,c,scanf,fork,system-calls,C,Scanf,Fork,System Calls,我的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

我的
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;
}
这是输出:

  • 我怎么修理

有关程序中发生的情况的解释,请参见此问题:。最重要的部分是:

终端由前台进程组控制。当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;
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,字符**argv)
{
整数操作数,运算符;
pid_t pid2=fork();
如果(pid2==0){//figlio2
printf(“因编号插入”);
scanf(“%d%d”,&操作数,&运算符);//即使我是“%d%d”。。。
printf(“操作数是%d,运算符是%d\n”,操作数,运算符);
}否则如果(pid2>0){
等待(空);
}
返回0;
}
注意,需要考虑的其他一些一般性改进:

  • 始终检查函数调用的返回值<在使用
    printf
    中的结果之前,应特别检查code>scanf。同样,应检查
    fork
    返回值是否存在错误
调用
scanf()
失败。如果代码检查了
scanf()
的返回值,那么它可能知道这一点。除2之外的任何返回值都表明发生了错误

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


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

Add
wait(NULL)
返回0之前调用父进程
。这是需要等待的原因:另外-始终检查输入函数(如
scanf()
)的返回值。根据“错误”链接,您没有输入两个预期的整数值,因此对
scanf()
的调用失败,我没有直接重复提到的问题,因为它解释了问题是什么,但没有提供这个问题的具体解决方案。