Read from pipe C

本小妞迷上赌 提交于 2019-12-13 05:08:26

问题


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]);

Help would be much appreciated!


回答1:


You need to create the pipe before the fork!

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




回答2:


Could you please elaborate more on what you are trying to do? One thing that is wrong here is you are calling the pipe() call after the fork, causing the parent as well as the child to have different copies of the file descriptors. You should create the pipe before the fork() call so that the two processes share the pipe.




回答3:


First of all: you have to call pipe before fork, otherwise there will be NO communication between processes.

Secondly: Your read before execlp does not have any sense, because you are not using information stored in buff anywhere. This one you'll have to explain to get any more help.

Also close stdin before calling dup.



来源:https://stackoverflow.com/questions/22244812/read-from-pipe-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!