0

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);
kntgu
  • 184
  • 1
  • 2
  • 14
  • `fd[0]` is the read end of the pipe. You're writing to it in the parent process and reading from the same end in the child process. Also, you're writing to it *before* the `dup2` call, meaning you're not writing to the standard output at that point. – bnaecker Mar 15 '18 at 19:19
  • I am using bidirectional pipes. – kntgu Mar 15 '18 at 19:21
  • Pipes are by definition unidirectional. What is `PIPE` doing? Is that creating a pair of pipes, socketpair, or some other bidirectional communication mechanism? – bnaecker Mar 15 '18 at 19:22
  • Edited my question... – kntgu Mar 15 '18 at 19:23
  • 1
    You're still writing and reading from the same socket, `fd[0]`. Data written on `fd[0]` will be read from `fd[1]` and vice versa. Also, you need to allocate some space using something like `char* data = malloc(10);` in the child process, otherwise you're reading data into an undefined memory location. – bnaecker Mar 15 '18 at 19:35
  • Thank you very much for your answer, I just missed the "data read and written on different descriptors" part. – kntgu Mar 15 '18 at 19:41

1 Answers1

1

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);
bnaecker
  • 6,152
  • 1
  • 20
  • 33