c - 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;
}
这是输出: 错误
- 我该如何解决?
解决方案
请参阅此问题以了解程序中发生的情况: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
应检查返回值是否有错误。
推荐阅读
- excel - 对数组求和
- yocto - 如何将 BeagleBoneBlack 的 pasm PRU 编译器集成到 Yocto 中
- sql - 我需要 sql position() 中的文本长度
- android - HM10 与 Arduino 和 Android BLE 之间的低功耗蓝牙大数据传输
- oop - 如何使用包含 where 的抽象多方法?
- javascript - 如何使用className(javascript)在div标签上应用onclick
- reactjs - React 没有渲染任何东西?
- shell - zsh - 如何引用以多个其他变量动态命名的变量?
- css - 修复了header,下面有视差英雄图,平滑滚动iOS和无JS
- c++ - 在 OpenCV 中未正确设置像素