问题
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