c - 在子进程中读取

标签 c unix stdin

我的作业有问题。

在父进程终止后,我必须从子进程中的终端读取数据。写得很清楚,父进程必须在执行子进程后立即死亡,因此我找到的解决方案(例如使用 wait() )对我来说没有用。

我的代码

int main(void)
{ 
    printf("start main\n");
    if(fork() == 0){
        char buffer[64];
        fgets(buffer, 64, stdin);
        printf("Child process: %s\n", buffer);
    }
    else printf("end main\n");
    //Using WAIT() here is not allowed in my assignment.
    return 0;
}

它不会等待我输入数据。看来父进程结束后,子进程处于后台,无法从终端读取任何数据。

结果

damian@damian-Virtualbox:-$ ./testuje
start main
end main
damian@damian-Virtualbox:-$ Child Process: 
echo test | ./testuje
start main
end
damian@damian-Virtualbox:-$ Child Process: test

程序应该做什么

print: start main
print: end main
then it should:
wait for user to type something
print: child process: text_typed_by_user

编辑:建议我使用 tee 命令。你知道如何用它来实现我想要的吗?

最佳答案

您可能想使用 vfork 而不是 fork(检查 documentation here ):

pid_t vfork(void);

vfork - create a child process and block parent

关于c - 在子进程中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34826761/

相关文章:

ssh - 如何让ssh从stdin接收密码

c++ - 初始化 C/C++ 多维数组时忽略大小

c - 加密实现 - 令人困惑的结果

objective-c - 奇怪的 "Switch Case"声明

windows - 如何使用 ANT 从 Windows XP 系统执行 UNIX 命令

linux - 使子进程在 waitpid 之前不是僵尸进程

c - 在 C 中从 stdin 读取写入到 stdout

C:基于区域的内存管理

c - 杀死父进程的所有子进程但让父进程保持事件状态

Python StringIO - 有选择地将数据放入标准输入