Sponsored Content
Top Forums Programming Child threads communicating with main thread via pipes Post 302667267 by Majortom71 on Friday 6th of July 2012 03:26:49 AM
Old 07-06-2012
I basically want to inform main that a client disconnected in order to decrement the thread counter. Right now my program is setup to only create a certain number of threads to serve the connecting clients. If the client disconnects the thread count needs to be decremented so that it does not max out and not allow further threads to be made for waiting clients.

Now I can use a global variable, but I am doing this to learn more about Unix system programming and I thought either pipes or message queues would be interesting to try out. My problem is I am not sure how my code can utilize this to send information from child thread to main thread.

I wrote some quick and dirty code as an to test out different ways of what I need to do.
In my code I commented where I want to send message back to main process.

I have client code if you do need I can post, but the code below should be sufficient.

Thanks for any help! Smilie

Code:
#include <stdio.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFFERSIZE	512
#define NTHREADS	10
#define SERVER_PORT 6001
#define POOL_SIZE 5

void *main_client_thread(void *arg);

typedef struct mainthreadArg
{
	int csocketId;
	int threadCounter;
}mtArg;

int main(int argc, char** argv)
{
	int csock, ssock;
	socklen_t addr_len;
	pthread_t cthread[NTHREADS];
	
	struct sockaddr_in addr;
	bzero((void *)&addr, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERVER_PORT);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr_len = sizeof(addr);
	
	/* socket */
	if((ssock=socket(PF_INET, SOCK_STREAM, 0))==-1)
	{
		fprintf(stderr,"Unable to create server socket\n");
		exit(1);
	}
	
	/* bind */
	if(bind(ssock, (struct sockaddr *)&addr, sizeof(addr))==-1)
	{
		fprintf(stderr,"bind failed.\n");
		exit(1);
	}

	
	/* listen */
	if(listen(ssock, POOL_SIZE)==-1)
	{
		fprintf(stderr, "listen failed.\n");
		exit(1);
	}
	
	mtArg ta;
	ta.threadCounter = 0;   /* thread counter */
	
	/* main loop to manage clients */
	while(1)
	{
		if(ta.threadCounter > NTHREADS)
		{
			printf("No more threads can be created. Sorry\n");
			exit(1);
		}
		
		/* accept */
		if((csock=accept(ssock, (struct sockaddr *)&addr, &addr_len))==-1)
		{
			fprintf(stderr, "accept failed.\n");
			exit(1);
		}

		ta.csocketId = csock;
		if((pthread_create(&cthread[ta.threadCounter], NULL, main_client_thread, &ta)) != 0)
		{
			fprintf(stdout, "pthread was not created\n");
			exit(0);
		}
		ta.threadCounter++;
	}
	
	return 0;
}

void *main_client_thread(void *arg)
{
	mtArg t = *(mtArg *)arg;
	int cli,cnt;
	cli = t.csocketId;
	cnt = t.threadCounter;
	
	int stayConnected = 1;
	int nread;
	/* int nwrite; */
	char buffer[BUFFERSIZE];
	
	while(stayConnected == 1)
	{
		bzero(buffer, sizeof(buffer));
		if((nread=read(cli, buffer, BUFFERSIZE)) > 0)
		{
			printf("Thread %d read %d bytes from client.\n", t.threadCounter, nread);
			printf("Thread %d buffer=%s\n", t.threadCounter, buffer);
		}
		else  /* client disconnected */
		{
			printf("nread failed.\n");
			t.threadCounter--;
			/* report back to main thread so that thread counter is decremented */
                        /* use pipe or message queue for this */
			stayConnected = 0;
		}
	}
	return NULL;
}

 

10 More Discussions You Might Find Interesting

1. Programming

Implementing 2 pipes between a parent and child process

Hi all, I'm trying to write a program that has some data it wants to send through a filter program(in this case tr), and then recieve the output from that filter program. The way I'm trying to do it is by setting up two pipes between the programs and piping the data in through one pipe and back... (2 Replies)
Discussion started by: bwgoudey
2 Replies

2. Programming

Can SIGTERM to main process kill the detached threads?

Hi, I am stuck up with a strange problem. I am writing an application - a kinda tracker that reads data from memcache and invokes theads to process each record of the memcache. I dont want to join all my threads because my tracker should poll the cache in regular intervals say sum 300... (2 Replies)
Discussion started by: deepti_v25
2 Replies

3. Shell Programming and Scripting

starting many child threads simultaneously

i have a parent process and 5 child process. As soon as the parent process is completed the 5 child processes need to start simultaneously (like multithreading) All I need to do in a shell script the child process is a function can any one help me on this thanks in advance (1 Reply)
Discussion started by: trichyselva
1 Replies

4. Programming

IPC - pipes between parent and child process

Hi guys, I'm having some problem here, I'm studying pipes, and i want to create a shell in C and at this point a don't want to use semaphores, instead I want to use tricks. Straight to the doubt: I've a parent and a child process, and both of them has some code to execute, and the child process... (5 Replies)
Discussion started by: pharaoh
5 Replies

5. Programming

Parent Thread Of Child Thread

Parent Thread Of Child Thread Suppose a process creates some threads say threadC and threadD. Later on each of these threads create new child threads say threadC1, threadC2, threadC3 etc. So a tree of threads will get created. Is there any way to find out the parent thread of one such... (1 Reply)
Discussion started by: rupeshkp728
1 Replies

6. Programming

creating multiple threads using single thread id

Hi all, Can I create multiple threads using single thread_id like pthread_t thread_id; pthread_create(&thread_id, NULL, &print_xs, NULL); pthread_create(&thread_id, NULL, &print_ys, NULL); pthread_create(&thread_id, NULL, &print_zs, NULL); pthread_join(thread_id, NULL); what... (2 Replies)
Discussion started by: zing_foru
2 Replies

7. Programming

unnamed pipes and threads

Hi! I am writing a C program that will create a child, child will create a thread and the thread will send a message to a unnamed pipe and will print the message before exiting. here is my work: #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include... (6 Replies)
Discussion started by: nimesh
6 Replies

8. Programming

Killing a Child Thread

What is the best way for a parent to kill a child thread that has blocked on a command it cannot finish and will never read another line of its code? Will pthread_cancel() work with a thread that will never stop processing its current line of code? Thanks. (4 Replies)
Discussion started by: Brandon9000
4 Replies

9. IP Networking

Message passing from child to parent using pipes

Hi, I am trying my hand in networking programming in C, and got stuck in piping. I was following some tutorial and did the forking like : while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) ... (4 Replies)
Discussion started by: abhi1988sri
4 Replies

10. UNIX for Advanced & Expert Users

How to kill a thread among several threads belongs to a process?

I would like to know is there any we can kill a single thread among multiple threads belongs to process? Since Signal action is process wise not per thread, i strongly feel that we can not or for that mater from external sources as well single thread can not be killed which is critical section... (2 Replies)
Discussion started by: murali242512
2 Replies
CTHREAD(3)						     Common Library Functions							CTHREAD(3)

NAME
Cthread - LCG Thread inferface SYNOPSIS
#include <Cthread_api.h> int Cthread_create(void *(*startroutine)(void *), void * arg); int Cthread_create_detached(void *(*startroutine)(void *),void *arg); int Cthread_join(int cid, int **status); int Cthread_mutex_lock(void *addr); int Cthread_mutex_trylock(void *addr); int Cthread_mutex_timedlock(void *addr, int timeout); int Cthread_mutex_unlock(void *addr); int Cthread_mutex_destroy(void *addr); int Cthread_cond_wait(void *addr); int Cthread_cond_timedwait(void *addr, int timeout); int Cthread_cond_signal(void *addr); int Cthread_cond_broadcast(void *addr); int Cthread_detach(int cid); int Cthread_kill(int cid, int signo); int Cthread_exit(void *status); int Cthread_self(void); int Cthread_getspecific(int *global_key, void **addr); int Cthread_setspecific(int *global_key, void * addr); DESCRIPTION
Cthread is a common API interface for multithreaded programs, although there is also support for nonthreaded application, where some of the Cthread functions then becomes useless. For non-thread applications see the section NON-THREAD ENVIRONMENT Any created thread is identified uniquely with a cid, standing for Cthread identifier. In multithread environment, Cthread is an interface to pthread functions on UNIX, and an interface to Win32 C-runtime library on Win- dows/NT. Cthread_create is creating a thread given its starting point startroutine and its arguments arg address. The thread is created with the default parameters, e.g. it is a joinable thread. Return value is the Cthread identifier cid , greater or equal to zero, or -1 on error. Cthread_create_detached takes the same arguments as Cthread_create and (tries) to create a detachable thread, which will then make it act as a daemon. This means that ressources used by this thread will be freed immediately when it terminates. On the other hand, such thread cannot be synchronized with other threads using the Cthread_join method. You have to remind that creating a detachable thread do not work immediately at the creation step on every thread implementation, in par- ticular in the DCE threads. If the implementation do not allow this at creation time, then Cthread_create_detached calls Cthread_create. Please have a look at Cthread_detach section. Return value is the Cthread identifier cid , greater or equal to zero, or -1 on error. Cthread_exit makes current thread exiting. If status isn't NULL, it is assumed to point to an integer whose value if the status that a Cthread_join would received, in case the thread is joinable. Please note that Cthread_exit is dangerous and non-recommended on Windows platform. Return value is 0 on success, or -1 on error. Cthread_kill sends signo signal number to the thread cid. This affect the status that a Cthread_join would received, in case the thread to be killed is joinable. Please note that Cthread_kill is not supported on DCE threads. Return value is 0 on success, or -1 on error. Cthread_join suspends the calling thread until the one identified with the Cthread identifier cid terminates. If the status parameter is not NULL, the status of the terminating thread cid is stored there. This status is the pointer returned by thread cid at its end. Return value is 0 on success, or -1 on error. Cthread_mutex_lock is an alias for Cthread_mutex_timedlock with a timeout of -1. Cthread_mutex_trylock is an alias for Cthread_mutex_timedlock with a timeout of 0. Cthread_mutex_timedlock is acquiring a mutex, creating it if necessary, on the addr address. The second parameter is the eventual timeout in seconds. If this parameter is < 0, the calling thread is suspended until it is granted access to addr , if it is zero, the calling thread will try to gain the lock, and if it is greater than zero the calling thread will wait up to timeout seconds. Please note that, in Cthread, a creation of a mutex is always associated with a creation of a conditionnal variable. See Cthread_cond_timedwait and Cthread_cond_broadcast_. Return value is 0 on success, or -1 on error. Cthread_mutex_unlock is unlocking the mutex that the calling thread is assumed to have acquired previously, calling Cthread_mutex_timedlock on the addr address. Cthread_cond_wait is an alias for Cthread_cond_timedwait with a timeout of -1. Cthread_cond_timedwait is waiting for a condition variable, which is, by default in Cthread, broadcasted, associated with a mutex previ- ously created on the addr address. Calling this function before the creation and the lock of a mutex, with Cthread_mutex_timedlock is a programming error. While the thread is waiting on a condition to arise on the addr address, the corresponding lock is released. It will be acquired as soon as the condition happens. Please note that the use of condition is subject to normal thread programming rules, e.g. the lock, a loop on a predicate, a wait inside the loop, and the unlock. If the timeout parameter, in seconds, is greater than zero, then the function will not suspend the calling thread more than this limit. Return value is 0 on success, or -1 on error. Cthread_cond_signal is an alias for Cthread_cond_broadcast. Cthread_cond_broadcast restarts threads that are waiting on a condition variable vs. addr address. Return value is 0 on success, or -1 on error. Cthread_detach is detaching the calling thread, identified with cid Cthread identifier. Whereas the normal thread packages that allow a thread to be detached at the creation step, see Cthread_create_detached, returns an error if such a detached thread tries to detach himself again, Cthread_detach will not, because of this different behaviour vs. different thread implementations: it is not possible everywhere to create a detached thread immediately, like in DCE threads. This means that if a user is creating a thread with Cthread_create or Cthread_create_detached, the created thread will, in any case, be allowed to call Cthread_detach: if the calling thread is not yet detached, it will be changed so forth, and if the calling thread is already detached, the return value will be 0. Return value is 0 on success, or -1 on error. Cthread_mutex_destroy is removing its corresponding entry in Cthread internal linked list, freeing all thread associated stuff, like the mutex itself, and the conditionnal variable (see Cthread_mutex_timedlock). Return value is 0 on success, or -1 on error. Cthread_self is returning the Cthread identifier cid of the calling thread. Return value is the cid (greater or equal to zero) on success, or -1 on error. Cthread_getspecific is creating and/or getting a thread-specific storage address for every instance of the global_key address, storing its result in addr location. The first time it is called, the stored result is NULL, next time it will be the address of the memory the user would have previously allocated and associated with the key using Cthread_setspecific. Return value is 0 on success, or -1 on error. Cthread_setspecific is associating a memory, starting at addr that he have previously allocated, with the global_key address. If he tries to do so without calling previously Cthread_getspecific, then such a call will be done internally. Return value is 0 on success, or -1 on error. ERRORS
Beyond the errno value, Cthread is setting the serrno value to generic values that can be: SECTHREADINIT LCG Thread interface initialization error A thread initialisation call failed. In principle, on UNIX this will be a call to pthread_mutex_init (and possibly pthread_mutex- attr_init) that failed, on Windows/NT this might be a call to CreateMutex. SECTHREADERR LCG Thread interface failure in calling your thread library A thread call to your native system library (like the pthread one on UNIX) failed. Please note that this is differentiated to the Cthread initialization and can happen if you are using too much thread keys, for example. This is really a run-time error only con- cerning your operating system thread interface. Any other system call failure, but not a thread one, and not at the initialisation step, will set serrno to SEINTERNAL SEOPNOTSUP Operation not supported This can be generated only if you compiled Cthread with a -DCTHREAD_PROTO flag that Cthread do not know about. Check your LCG con- figuration site.def. SEINTERNAL Internal error You can have more information by compiling the Cthread package with the flag -DCTHREAD_DEBUG, and catching the printout on your stderr stream. This is any system call that failed (like malloc()), except those to the thread library (for which SECTHREADERR or SECTHREADINIT is to be found), or any critical internal run-time error (such as a non correct value found in some Cthread internal structures). SETIMEDOUT (routines with a timeout parameter only) Timed out You called a routine with a timeout value greater than zero that reached the maximum number of timeout seconds in waiting state. EINVAL Invalid parameters You called a routine with invalid parameter(s). Please check your code. EXAMPLES
Here is an example with thread-specific data #include <Cthread_api.h> /* Cthread include file */ #include <stdio.h> /* For I/O functions and definitions */ #define NTHREADS 5 /* Number of threads */ #define NLOOP 5 /* Number of loops in threads */ static int global_key; /* Internal Prototypes */ void *mythread(void *); void testit(); int main() { int i, n; for (i=1; i <= NTHREADS; i++) { if ((n = Cthread_create(&mythread,NULL)) < 0) { exit(EXIT_FAILURE); } else { fprintf(stderr,"[main] --> Created Cthread ID %d ",n); } } sleep(NTHREADS); exit(EXIT_SUCCESS); } void *mythread(void *arg) { int i; /* Call the same routine NLOOP times */ for (i=1; i <= NLOOP; i++) { testit(); } return(NULL); } void testit() { char *addr = NULL; int n; if ((n = Cthread_detach(Cthread_self()))) exit(EXIT_FAILURE); if ((n = Cthread_getspecific(&global_key,(void **) &addr))) exit(EXIT_FAILURE); if (addr == NULL) { addr = malloc(100); fprintf(stderr,"[%d] --> new 0x%x ", Cthread_self(),addr); if (Cthread_setspecific(&global_key,addr)) exit(EXIT_FAILURE); } else { fprintf(stderr,"[%d] --> old 0x%x ", Cthread_self(),addr); } sprintf(addr,"[%d] Print with TSD buffer : Cthread ID=%d ", Cthread_self(),Cthread_self()); fprintf(stderr,addr); return; } NON-THREAD ENVIRONMENT In such an environment, almost all methods becomes no-op, except: Creation of process(es): Cthread_create Cthread_create_detached (equivalent to Cthread_create) Cthread_join Use of "Process"-specific variables: Cthread_getspecific Cthread_setspecific For these two last functions, Cthread will garbage itself its eventual list of "Process"-specific variables. This means that, as in a thread environment, the user will not have to free memory allocated and registered with a call to Cthread_setspecific. SEE ALSO
pthread, DCE, LinuxThreads, Win32 AUTHOR
LCG Grid Deployment Team LCG
$Date: 2005/03/29 09:27:18 $ CTHREAD(3)
All times are GMT -4. The time now is 06:04 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy