【问题标题】:How do I get input from a terminal in a separate process?如何在单独的进程中从终端获取输入?
【发布时间】:2021-04-24 20:56:45
【问题描述】:

我尝试使用 fork() 以便在我的程序与服务器交换消息的同时从终端获取输入,但结果是一个程序在我按下 Enter 之前就在读取输入。

所以如果我使用这个:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <mqueue.h>
#include <sys/msg.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>


int main(int argc, char ** argv){
    int pid = fork();

    if (pid == 0){
        for(int i =0; i<10; i++){
            char command[255];
            fgets (command, 255, stdin);
            printf("%s\n", command);
            sleep(1);
        }
        exit(0);
    } else {

    }
}

当我运行程序时,我不做任何事情就会发生这种情况:

�   
�   
�   
�   
�   
�   
�   
�   
�   
�   

如果我使用 scanf("%s\n", command);fgets (command, 255, stdin); 以及我能找到的所有其他变体,就会发生完全相同的事情......

如果我将代码更改为

int main(int argc, char ** argv){
    int pid = fork();

    if (pid != 0){
        for(int i =0; i<10; i++){
            char command[255];
            fgets (command, 255, stdin);
            printf("%s\n", command);
            sleep(1);
        }
        exit(0);
    } else {

    }
}

然后它工作正常,但我希望我的输入读取进程成为一个子进程,因为原始进程的 pid 是提供给我的服务器进程的信息的一部分。

一些附加信息:

我在编译程序时使用makefile:

cc = gcc -Wall -D_DEFAULT_SOURCE -std=c11 -g

all: server client

dirs:
    mkdir -p build

server: dirs utils server.c
    $(cc) -c server.c -o build/server.o
    $(cc) build/server.o build/utils.a -o server
    
client: dirs utils client.c
    $(cc) -c client.c -o build/client.o
    $(cc) build/client.o build/utils.a -o client
    
utils: dirs utils.c
    $(cc) -c utils.c -o build/utils.o
    ar rcs build/utils.a build/utils.o
    
problem: dirs problem.c
    $(cc) -c problem.c -o build/problem.o
    $(cc) build/problem.o -o problem

clean:
    rm -Rf build *.out *.so *.o *.a

【问题讨论】:

  • @Jakub Kmiecik - 如果您的系统如您所描述的那样运行,则它有缺陷。但显示的程序不完整。
  • 最可能的解释是 A)您在进行更改后没有重新编译,B)您未显示的代码部分存在语法错误,导致无法创建新的可执行文件, 或 C) 您运行的可执行文件不是编译器创建的新可执行文件。
  • 好吧,虽然这对我来说可能是一个非常愚蠢的错误,如果这不是我错误使用该功能的问题,那么似乎我必须编辑我的问题以包含更多细节,所以我现在正在这样做。

标签: c


【解决方案1】:

父进程死亡,子进程被收割者或子收割者进程采用。因此,您的子进程与终端“分离”,因此,父进程必须调用wait()waitpid()

 void init_reader(){
    int pid = fork();

    if (pid == 0){
        for(int i =0; i<10; i++){
            char command[255];
            fgets (command, 255, stdin);
            printf("%s\n", command);
            sleep(1);
        }
        exit(0);
    } else {
       wait(NULL);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多