Exiting a Thread after Communication Process is Over

I am working on a Multi threaded server application in C using Pthreads.How can i exit a thread and free the resources being used by it after the client sends a request for closing the connection. I am pasting my code below

Main.C

#include "extern.h" int thread_counter = 0; int rc; void main(int argc, char** argv){ int sock_desc = 0, connfd = 0; struct sockaddr_in serv_addr; int clntSock; struct sockaddr_in echoClntAddr; int n = 0; pthread_t thr; sock_desc = socket(AF_INET, SOCK_STREAM, 0); if(sock_desc < 0 ) dieWithError("Unable to open Socket\n"); fcntl(sock_desc, F_SETFL, fcntl(sock_desc, F_GETFL, 0) | O_NONBLOCK); memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(7024); if(bind(sock_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) dieWithError("bind failed\n"); if(listen(sock_desc,MAX_CONNECTIONS) < 0) dieWithError("listen failed\n"); clntSock = sizeof(struct sockaddr); int i =0; while(1){ connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr,(socklen_t*)&clntSock); if(connfd > 0){ puts("Connection accepted"); if(pthread_create( &thr, NULL , connection_handler , (void*)connfd) < 0){ perror("could not create thread"); } puts("Handler assigned"); } } } void dieWithError(char *errormsg){ printf("%s", errormsg); }

HandleConnection.C

#include "extern.h" void *connection_handler(void *socket_desc){ int sock = (int) socket_desc; int read_size; char client_message[2000]; int i; int rc = 5; while(1){ read_size = recv(sock , client_message , 2000 , 0); if(read_size > 0){ client_message[read_size] = ''; printf("%s",client_message); } memset(client_message, 0, 2000); if(read_size == 0){ puts("Client disconnected"); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL); fflush(stdout); rc = close(sock); break; } else if(read_size == -1){ perror("received failed"); break; } } }

How and where should i write a routine to exit a Thread after its work is Over.i tried using pthreads_cancel but it didn't helped,reason might be i haven't used it properly.

Category:c# Time:2019-01-05 Views:10

Related post

  • Is there a way to cleanly exit out of a thread which is processing data from a (never-ending) generator? 2010-10-01

    Here's the issue: I have a thread which runs a for-loop reading from a generator, doing some processing on that data, etc.. The generator always has data coming in, so no StopIteration exception is ever raised by it. I would like to stop this thread

  • Exiting a thread blocking on TCP read in C# 2009-08-24

    My server/client start a new thread "readerThread()" for reading incoming tcp traffic. This thread blocks on read(). How can i exit this readerThread(). One way is to start another thread which closes the socket when the thread is to be exited so the

  • Signalling all threads in a process 2010-11-17

    Without keeping a list of current threads, I'm trying to see that a realtime signal gets delivered to all threads in my process. My idea is to go about it like this: Initially the signal handler is installed and the signal is unblocked in all threads

  • C# - Stop a thread after XX seconds 2011-08-26

    I'm using a thread in C# and I would like it to stop after 40 seconds. In fact, I start it, it runs for 40 seconds and then it shoudl stop. Is it possible to use a timeout or a timer ? --------------Solutions------------- There are two approaches: 1.

  • Get StartAddress of win32 thread from another process 2011-12-30

    Background: I've written a multi-threaded application in Win32, which I start from C# code using Process class from System.Diagnostics namespace. Now, in the C# code, I want to get the name/symbol of the start address of each thread created in the Wi

  • Is it safe to thread after forking? 2010-09-16

    I've learned that you should usually stick with either forking or threading to avoid running into very strange and extremely hard-to-debug problems, so until now I always did exactly that. My problem with the matter is that when I stick with only for

  • Exiting gracefully from a multithreaded process 2010-10-22

    I'm running a multi-threaded C program (process?) , making use of semaphores & pthreads. The threads keep interacting, blocking, waking & printing prompts on stdout continuously, without any human intervention. I want to be able to exit this

  • passing variable to a thread after it already started 2011-01-26

    i am newbie in C++ and boost. As part of my master thesis, i wrote a program which simulate a statistical model. During the computation, i use boost::thread to process my "center of mass vector", for saving some computation time. So far so good. Now,

  • Execute external process from java. Got the output after the process terminated, but need it before termination 2011-07-19

    Why I get the output of the process after the process has terminated? I need to get the process output "live", while the process is running and not after the process has terminated. I would like to run a process like a jboss, which is logging on the

  • Giving access to shared memory after child processes have already started 2011-09-14

    How do I give child processes access to data in shared memory if the data is only available after the child processes have been spawned (using multiprocessing.Process)? I am aware of multiprocessing.sharedctypes.RawArray, but I can't figure out how t

  • join thread after start_new_thread 2012-02-11

    below function exits after 3 seconds when i run it separately, but when i call it in a thread it never exits. kindly suggest what is wrong in this code. def display(val1, val2): root = Tk() clock = Label(root, font=('times', 20, 'bold'), bg='white')

  • Exit Shell Script Based on Process Exit Code 2008-09-18

    I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code? --------------Solutions------------- After each command, the exit code can be found in the $? variabl

  • scheduling a Thread after a Thread in iphone application 2009-10-28

    I want to schedule a thread after a thread completion. Is it possible ? How? For example ( to specify my need ) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 1. response - schedule myThread // 2. response - sched

  • Why are threads called lightweight processes? 2010-02-15

    A thread is "lightweight" because most of the overhead has already been accomplished through the creation of its process. I found this in one of the tutorials. Can somebody elaborate what it exactly means? --------------Solutions------------- The cla

  • Why is there no .NET Community Process? 2010-03-12

    I was doing some research into general topics of software engineering and I came across the Java Community Process website: The JCP is the mechanism for developing standard technical specifications for Java technology. Anyone can register for the sit

  • Killing thread after some specified time limit in Java 2010-04-28

    Is there a way to kill a child thread after some specified time limit in Java? Edit: Also this particular thread may be blocked in its worst case (Thread is used to wait for a file modification and blocks until this event occurs), so im not sure that

  • Are threads from multiple processes actually running at the same time 2010-06-04

    In a Windows operating system with 2 physical x86/amd64 processors (P0 + P1), running 2 processes (A + B), each with two threads (T0 + T1), is it possible (or even common) to see the following: P0:A:T0 running at the same time as P1:B:T0 then, after

  • kill boost thread after n seconds 2010-10-27

    I am looking for the best way to solve the following (c++) problem. I have a function given by some framework, which returns an object. Sometimes it takes just miliseconds, but on some occasions it takes minutes. So i want to stop the execution if it

  • How to stop asynchronous thread after 5 seconds of running 2010-11-24

    Have to create thread and run it for 5 seconds, then I want to stop. How can I do that? I can't do anything with time/milliseconds. THX. --------------Solutions------------- Use the AsyncTask.cancel(true) method. Threading in java is cooperative - yo

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.485 (s). 13 q(s)