Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何在子进程中正确接收键盘的标准输入?_Linux_Bash_Terminal_C - Fatal编程技术网

Linux 如何在子进程中正确接收键盘的标准输入?

Linux 如何在子进程中正确接收键盘的标准输入?,linux,bash,terminal,c,Linux,Bash,Terminal,C,我在Linux上运行以下C程序 节目 // program.c #include <stdio.h> #include <unistd.h> int main() { if (fork() == 0) { // child process int a, b; scanf("%d %d", &a, &b); printf("%d + %d = %d\n", a,

我在Linux上运行以下C程序

节目

// program.c
#include <stdio.h>
#include <unistd.h>

int main() {
    if (fork() == 0) { // child process
        int a, b;
        scanf("%d %d", &a, &b);
        printf("%d + %d = %d\n", a, b, a + b);
    }
    return 0;
}
实际行为

$ ./program
1 2
1 + 2 = 3
$ ./program
$ 1222245440 + 32764 = 1222278204
当我在终端中运行程序时,它会产生奇怪的输出,如
1222245440+32764=1222278204
,并且不会等待我输入。有没有办法解决这个问题

我认为问题在于子进程的标准输入和输出流没有连接到终端。相反,父进程的流是附加的

父进程不等待子进程,而是立即返回。孤儿无法从终端读取,“奇怪输出”来自
a
b
。查看scanf返回的内容,运行以下代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int wstatus;
    if (fork() == 0) { // child process
        int a, b, n;
        n=scanf("%d %d", &a, &b);
        printf("(%d returned) %d + %d = %d\n", n, a, b, a + b);
    }
//    wait(&wstatus);
    return 0;
}
#包括
#包括
#包括
int main(){
int wstatus;
如果(fork()==0){//子进程
int a,b,n;
n=scanf(“%d%d”、&a和&b);
printf((%d返回)%d+%d=%d\n“,n,a,b,a+b);
}
//等待(&wstatus);
返回0;
}
您很可能会得到类似于
(-1 returned)1222245440+32764=1222278204
的结果。然后取消注释
等待
并重试