C/Linux - Server <-> Terminal communication with named pipes C/Linux - Server <-> Terminal communication with named pipes multithreading multithreading

C/Linux - Server <-> Terminal communication with named pipes


Daniel,

I implemented a similar server before, you can listen a terminal, and when the terminal finishes the message you can fork the process and send the response back on the child process, whereas in the parent process in a loop you create another listener for the next terminal, as ccarton said:

Something like this:

while (1) {   newsockfd = accept(sockfd,               (struct sockaddr *) &cli_addr, &clilen);   if (newsockfd < 0)     error("ERROR on accept");   pid = fork();   if (pid < 0)     error("ERROR on fork");   if (pid == 0)   {     close(sockfd);     dostuff(newsockfd);     exit(0);   }   else     close(newsockfd); } /* end of while */

You can find a complete explanation here: http://www.linuxhowtos.org/C_C++/socket.htm

Under "Enhancements to the server code" Section.

Hope this helps.


One way to synchronize the server with the terminal is using System V semaphore. The semaphore is taken by a terminal before start "listening" to the channel for "x" minutes. If a message arrive, the terminal process it an send the response back, else, if timeout occurs it just release the semaphore so other terminal can start listening. The problem with this is that you loose the ability to process several message in parallel.

Another approach is as @Moulin said to use an id in (for example the PID returned by fork()) in your structures command_t and reply_t.