In my program (main.c) I fork a process and then I need to send data via pipe to child process. After execl system call child process continues its life in process.c file. With setting standard input of that child to file descriptor of its parent I try to send data from parent process to child process. But child process cannot reach any input and I couldn't understand that why this problem occurs. Many thanks in advance.
main.c
#define PIPE(fd) socketpair(AF_UNIX, SOCK_STREAM, PF_UNIX, fd)
...
char* data="data";
int fd[2];
PIPE(fd);
write(fd[0],data,sizeof(data));
if(fork()==0){
dup2(fd[0],0);
close(fd[0]);
close(fd[1]);
execl("process","process",x,y,0);}
process.c
...
char* data;
read(0,data,10);
printf("%s\n",data);
You're reading and writing on the same socket.
Creating a pair of sockets using socketpair(2)
allows you to communicate bidirectionally, so that data written on the first socket is read from the second, and vice versa.
Here fd[0]
refers to the same socket in the parent and child processes, so the parent is writing to the first socket and child is trying to read from the same socket. The data the parent writes will appear on the second socket, fd[1]
in this case.
So you need to do:
dup2(fd[1], 0); // make stdin of the child refer to the *second* socket
and
char data[11] = {'\0'}; // make sure to allocate space
read(STDIN_FILENO, data, sizeof(data) - 1);