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;
}
这是输出:
- 我怎么修理
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;
}
注意,需要考虑的其他一些一般性改进:
- 始终检查函数调用的返回值<在使用
中的结果之前,应特别检查code>scanf。同样,应检查printf
返回值是否存在错误fork
scanf()
失败。如果代码检查了scanf()
的返回值,那么它可能知道这一点。除2之外的任何返回值都表明发生了错误
scan()在第一个“输入格式转换”说明符上失败,因此它从未查看第二个“输入格式转换”说明符
当调用
scanf()
中的整数“输入格式转换”说明符失败时,目标变量设置为0。第二个变量显示在堆栈上的“位置”内存中的垃圾。Addwait(NULL)代码>在返回0之前调用父进程
。这是需要等待的原因:另外-始终检查输入函数(如scanf()
)的返回值。根据“错误”链接,您没有输入两个预期的整数值,因此对scanf()
的调用失败,我没有直接重复提到的问题,因为它解释了问题是什么,但没有提供这个问题的具体解决方案。