How can I use pipe in this C ++ code?

I have big problems because I don’t know how to do this. I need to create only 2 processes that can exchange information. This is the code:

/* Wrappers */ this->sock_fd = this->w_socket(); this->w_bind(); this->w_listen(); std::cout << "[info] Server is running..." << std::endl; while(1) { /*Connection stuff */ struct sockaddr_in client_addr; int client_fd = this->w_accept(&client_addr); char client_ip[64]; int client_port = ntohs(client_addr.sin_port); inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip)); std::cout << "[info] Connection from (" << client_ip << ", " << client_port << ")" << std::endl; /*Login manager*/ ... /* Crate PID */ int pid = fork(); if (pid == 0) { close(this->sock_fd); this->manage(client_fd, client_ip, client_port); exit(0); } /* End connection */ close(client_fd); } 

Well. When the client successfully authenticates after the login manager, it can send data to the server. If the client is connected and the other is registered, the second should push the first client with the message "You were disconnected." How can I use fork and pipe for this? I tried to read something, but I'm a little confused.

Thanks.

+4
source share
2 answers

I am not sure about the specific project of your project, but if you use fork () to create a new client from an existing one and you want to use pipe () to communicate, here is a sample code.

 int pfds[2]; //pipe() always return pair of file descriptors(fds). char buf[30]; pipe(pfds); //fds will be stored in pfds. if (!fork()) { printf(" CHILD CLIENT: writing to pipe\n"); write(pfds[1], "New Client", 11); printf(" CHILD CLIENT: exiting\n"); exit(0); } else { printf("PARENT CLIENT: reading from pipe\n"); read(pfds[0], buf, 11); printf("PARENT CLIENT: read \"%s\"\n", buf); //Take appropriate Action upon read!!! wait(NULL); } 

I personally think that there are better options than using pipes for this type of communication (signals or shared memory).

+1
source
0
source

All Articles