C++ socket, fork & pipes

Hello, I'm stuck and this is a matter which I need to resolve quite fast (but I couldn't post in the "Emergency" section); the problem is this :

I have created a chat program in which the client sends the sentence to the server and then the server should send it to all the clients connected, which is done with a "for" and a vector of all new_fd connections. So I suppose (correct me if I'm wrong) the easiest way is that in the server I fork, the child process recieves the sentence; then sends it through a pipe to the parent process which in turn sends it to all clients. But for some reason the pipe doesn't work! In the parent process it starts "read"ing even before the writing has begun; and it reads nothing, no matter what I do it can't transmet data. Here is the code :

pid_t pid = fork();
char buffer[100];
int fd[2];
pipe(fd);
int nbytes;
char ready[4];
    if(pid==0) {

while(true) {
        close(sockfd);
        close(fd[0]);

        "recieve sentence through char* reception)"
        write(fd[1], "yes", 4);
        write(fd[1], reception, taille);
    }

    }
        else if (pid>0) {
            close(new_fd);
            close(fd[1]);
       nbytes = read(fd[0], ready, 4);
      cout<<ready<<endl;
      //ready couts NOTHING

       nbytes = read(fd[0], buffer, sizeof(buffer));

if(ready=="yes") {
  "send data to all clients"
            }
...

You create the pipe after you fork. The pipe the child gets, and the pipe the parent gets, are created independently hence not the same pipe. There will be no communication between parent and child.

Create the pipe before the fork and you'll have the same pipe in both, connecting the two.

Remember that the copies are completely independent. Be very sure to close all ends of the pipe you're not using -- close the read-end in the parent, and the write-end in the child! Otherwise you may end up hanging when the child is done reading but, with a read-end left open in the parent, write() still doesn't fail.

1 Like

Oh yes, I didn't see that. The solution was extremely simple, thanks for your clear answer!