我的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
请参阅以下问题,以了解您的程序中正在发生的情况:Child process cannot read after the exiting of parent process。最重要的部分:
终端由前台进程组控制。当外壳程序调用父级时,它将使父级成为前台进程组的领导者。子级继承该组并有权访问终端。
但是,当父级退出时,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
返回值是否有错误。对scanf()
的呼叫失败。如果代码检查了scanf()
的返回值,则该代码可能已经知道这一点。除2以外的任何返回值都将指示发生了错误。
第一个“输入格式转换”说明符的scan()失败,因此它从未查看第二个“输入格式转换”说明符。
当对scanf()
的调用中的整数“输入格式转换”说明符失败时,目标变量将设置为0。第二个变量在堆栈中的位置显示内存中的所有垃圾。