user434885
user434885

Reputation: 2018

Multiple threads with multiple alarms in C

I have a client-server application, running on a threaded server, which requires that each connection from a client create a new thread, the client has to wait x seconds before being served, currently i am using a sleep call in the beginning of each thread function to make this happen, but i would like to use alarms(SIGALARM) how would i go about doign this ?

int main()
{
        int sd,connfd,retbind;
        struct sockaddr_in serveraddress,cliaddr;
        socklen_t len;
        pthread_t th1;
        char buf[100];

        sd = socket( AF_INET, SOCK_STREAM, 0 );
        if( sd < 0 )
        {
                error_exit(SYSTEM_ERROR, "Socket");
        }

        memset( &serveraddress, 0, sizeof(serveraddress) );
        serveraddress.sin_family = AF_INET;
        serveraddress.sin_port = htons(MYPORT);
        serveraddress.sin_addr.s_addr = htonl(INADDR_ANY);

        retbind=bind(sd,(struct sockaddr*)&serveraddress,sizeof(serveraddress));
        if(-1==retbind)
        {
                error_exit(SYSTEM_ERROR, "Bind failed");
        }

        listen(sd,5);

        printf("-----------------------------------------\n");
        printf("Server running on port number %d\n", MYPORT);
        printf("------------------------------------------\n\n");

        for(;;)
        {
                printf("Waiting for connection...\n");

                len=sizeof(cliaddr);

                connfd=accept(sd,(struct sockaddr*)&cliaddr,&len);
                if (connfd < 0)
                {
                        if (errno == EINTR)
                                printf("Interrupted system call ??");
                        else
                                error_exit(SYSTEM_ERROR, "Connection");
                }

                printf("Connection from %s\n",
                inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)));

                pthread_create(&th1,NULL,thread_func,(void*)connfd);


        }

}

void* thread_func(void *connfd)
{
        socket_ip buffer;
        int pointer = 0, n;

        pthread_detach(pthread_self());

         sleep(30);

        readWriteFile( (int)connfd, &buffer);

        show_packet(&buffer);

        close((int)connfd);

        pthread_exit(NULL);
}

for example if a client request is received at 10 secs, 20 secs and 25 sec they should be served at 40 secs, 50 secs and 55 secs.

Help :/

Upvotes: 1

Views: 1801

Answers (1)

You probably want to use multiplexing calls like select or pselect or poll. See also the select tutorial man page. And you could use posix timers

And many libraries provide you with good event handling like e.g. libevent, Glib event loop from Gtk etc etc...

Upvotes: 2

Related Questions