Reputation: 331
Im trying to make a Tic Tac Toe game with server-client using FIFO(named pipe) and shared memory.
The first step is to write the pid of the client process to the FIFO. And in the server process i need to wait until 2 pids was passed in the FIFO (from 2 different client process).
Right now im just doing 2 read from the pipe but it's not works proper. Do i need to read in a while loop or something?
The client code:
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void main()
{
int fd;
int pid=getpid();
pid_t pid1=getpid();
fd=open("fifo_clientTOserver",O_WRONLY);
write(fd,&pid1,sizeof(pid_t));
printf("%d\n",pid1);
while(1);
}
The server code:
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void main()
{
int fd;
pid_t pid;
ftok("shmdemo.c","j");
mkfifo("fifo_clientTOserver",400);
fd=open("fifo_clientTOserver",O_RDONLY);
read(fd,&pid,sizeof(pid_t));
printf("%d",pid);
read(fd,&pid,sizeof(pid_t));
printf("%d",pid);
//sleep(2);
}
I want that the server will wait until 2 clients are running, how should i do that?
Thank you very much, Asaf.
Upvotes: 0
Views: 1281
Reputation: 400069
One way to organize logic like this is as a finite-state machine for the server process.
It will boot up in some kind of initial state, then enter a state in which is waits for clients to connect, and also for already-connected clients to send PIDs. These are two separate events, and can happen in any order. Once two clients are connected and have sent their PIDs, the server can enter a state in which it initializes a game, and so on.
A state machine is a handy way of modelling such changes.
In terms of code, if your server doesn't need to do things all the time (but only in response to actual client communication, i.e. players making moves), it's easiest to organize it with a central loop that reads client data (and accepts new clients), then maybe has a switch/case
statement to deal with the data depending on the state it's in, or something.
Upvotes: 1