从管道C读取 [英] Read from pipe C

查看:107
本文介绍了从管道C读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个新进程来运行xxx程序,加载xxx程序,将从管道读取的数据发送给"xxx",但是无论何时我都会收到此错误错误:无法从stdin读取"我尝试编译.

I need to create a new process to run the xxx program, load the xxx program, send 'xxx' the data read from a pipe, but I'm getting this error, "Error: could not read from stdin" whenever I try to compile.

pid_t pid;
pid = fork();
int fd[2]; 
int ret;

ret = pipe(fd); 

if (ret == -1)
{
    perror("pipe failed");
    exit(1);
}

if (pid == -1)
{
    perror("fork failed");
    exit(1);
}

else if (pid == 0) //Child
{
    char buff[10];
    int validate;
    close(fd[1]);
    dup2(fd[0], STDIN_FILENO); 
    close(fd[0]);
    read(STDIN_FILENO, buff, sizeof(buff)); 
    xxx = execlp("./xxx", "./xxx", NULL); //run xxx
    exit(validate);
}

else //Parent //WRITE STDIN TO PIPE
{
    close(fd[0]); 



    //writes data to pipe



    close(fd[1]);

我们将不胜感激!

推荐答案

您需要在派生之前创建管道!

You need to create the pipe before the fork!

以下是有关代码的代码及其修复方法 C管道,叉子, dup和exec()

Here is the code + fix of how it should be done C pipe, fork, dup, and exec()

这篇关于从管道C读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆