I’m trying to create a two-way communication between parent and child processes using 2 pipes using C on Linux. The parent is my program and the child is just a random program (say “cat”).
I try to uses read() in parent to read child output, but it gives me errno 9, which is Bad file descriptor.
The following is my code
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define Read 0
#define Write 1
#define ParentRead read_pipe[1]
#define ParentWrite write_pipe[0]
#define ChildRead write_pipe[1]
#define ChildWrite read_pipe[0]
int main()
{
int data_processed;
/** Pipe for reading for subprocess */
int read_pipe[2];
/** Pipe for writing to subprocess */
int write_pipe[2];
char buffer[100];
memset(buffer, '\0', 100);
if (pipe(read_pipe) == 0 && pipe(write_pipe) == 0)
{
pid_t pid = fork();
if (pid == (pid_t)-1)
{
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
else if (pid == (pid_t)0) //Child process
{
close(Read);
close(Write);
close(ParentRead);
close(ParentWrite);
dup(ChildRead);
dup(ChildWrite);
execlp("cat", (char*)NULL);
exit(EXIT_FAILURE);
}
else { //Parent process
close(ChildRead);
close(ChildWrite);
write(ParentWrite, "abc", 3);
int r = read(ParentRead, buffer, 99);
printf("%d %d", r, errno);
puts(buffer);
}
}
exit(EXIT_SUCCESS);
}
If you want to redirect stdin and stdout to pipes, you need to use dup2(2) system call.
P.S.
Also I found wrong directions of reading/writing in pipes. Here is the correct way
Remember: pipe[0] is fd for reading, pipe[1] is fd for writing.
And one more error, in execlp. Do not forget to set the first argument you send to the executed programm as a name of the program