I'm trying to implement a concurrent server in C using a daemon process and fifo (named pipes). My server and client applications successfully communicate but I want my server to handle multiple client requests concurrently. To handle multiple client requests, I have to create separate worker processes using double fork technique. I think I need to fork my worker process at the beginning of the server's infinite loop.
However, with this way server creates tons of processes and never stops to listen new client request. At some point I should block creating new processes but I can't figure out how to do it. I think exit(0)
function at the end of the second child should do it and kill the second child process but it seems not working and program keeps creating new processes in an infinite loop.
Server:
createDaemon(argv[1]);
umask(0);
mkfifo(serverFifoPath, 0666)
int serverFd = open(serverFifoPath, O_RDONLY);
int dummyFd = open(serverFifoPath, O_WRONLY);
signal(SIGPIPE, SIG_IGN)
for(;;)
{
syslog(LOG_NOTICE, "DAEMON STARTED");
pid_t pid;
if ( (pid = fork()) < 0)
{
syslog(LOG_ERR, "fork error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid == 0)
{ /* first child */
if ( (pid = fork()) < 0)
{
syslog(LOG_ERR, "fork error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
exit(0); /* parent from 2nd fork == 1st child */
}
/* second child. */
syslog(LOG_NOTICE, "second child, pid = %d\n", getpid());
//Read PID of the client
pid_t clientPID = 0;
read(serverFd, &clientPID, sizeof(clientPID))
//Server make other reads here
//and other server operations
exit(0); /* I think this exit(0) should kill the second child
after processing client request but it seems not
working and program creates many processes*/
}
/* wait for first child */
if (waitpid(pid, NULL, 0) != pid)
{
syslog(LOG_ERR, "waitpid error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
//original process
}
int clientFd = open(clientFifo, O_WRONLY);
//Server writes to fifo here
close(clientFd);
}
Client:
mkfifo(clientFifo, 0666);
int serverFd = open(serverFifoPath, O_WRONLY);
//Client writes here
int clientFd = open(clientFifo, O_RDONLY);
unlink(clientFifo);
//Client reads here
And I got my createDaemon
function from here: Creating a Daemon in Linux