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
CGLOBALS(3)						     Common Library Functions						       CGLOBALS(3)

NAME
Cglobals - LCG thread-specific global variables interface SYNOPSIS
#include <Cglobals.h> void Cglobals_init( int (*getspec) (int *key, void **addr), int (*setspec) (int *key, void *addr), int (*getTid) (void) ); int Cglobals_get(int *key, void **addr, size_t size); void Cglobals_getTid(int *Tid); int C__serrno(); int C__rfio_errno(); int C__Copterr(); int C__Coptind(); int C__Coptopt(); int C__Coptreset(); char *C__Coptarg(); int C__h_errno(); DESCRIPTION
Cglobals is the interface where are defined all necessary functions that always return a thread-specific value of global variables. Each package of LCG that needs to externalize thread-specific global variables contains in its header, if compiled with threads turned on (e.g. the default), a set of: an extern definition to a function contained in Cglobals a #define macro that replaces all occurences of any global variable that needs to be thread-specific to this Cglobal's function. In order to satisfy packages not compiled with threads turned on, or that do not initialize LCG Thread Interface's Cthread, any such global variable is also explicitly defined in Cglobals. For example, taking the global error variable serrno, Cglobals source code contains: an explicit definition of this variable serrno an explicit definition, with source code, of a function C_serrno() that does only the following: if Cglobals_init was not (successfully) called, return the address of the global variable serrno else return the address of a thread-safe specific memory, instanciated at the first call to this function, that holds the content of the current instance of the thread-specific value of serrno The following description of Cglobals_init function is explaining internals of Cglobals and Cthread. In theory no LCG application need to call Cglobals_init, you can skip if you want the following paragraphs, and concentrate only on the other functions descriptions. Cglobals_init is bundled to work with the LCG Thread Interface's Cthread. That is, any implicit or explicit call to Cthread always makes sure that Cglobals_init is called, with three arguments that are: a getspec function address that, given a static key address, returns the address of a Thread-Specific memory into addr content. This uses an internal structure inside Cthread, allocated on the heap, that is associated bijectively to key address. Cthread always explicitly allocates such internal structure to any key address if it is unknown at the moment of the call to getspec. In such a case it will return a NULL value into addr , and it will be the responsability of Cglobals to allocate memory on the heap and to say to Cthread that this newly allocated memory is the one to associate with key address, using setspec. If the internal structure in Cthread associated bijectively to key yet exists, getspec only returns what it knows about the thread- specific memory associated with it, which is a void * member inside the same internal structure mentionned above. a setspec function address that, given the key address and the addr value, previously instanciated with a getspec call, and possibly allocated on the heap by Cglobals if necessary, will internally explicitly call the Operating System Thread-Specific functions that will put the value of address as something thread-specific, bijectively associated to another member of the internal structure of Cthread, itself bijective to key. a getTid function address that returns an unique integer identifier associated with any thread. Cglobals_get returns in addr content the address of a thread-specific memory, e.g. thread-safe, that is bijectively associated with the address of a *static*, e.g. constant, address key , that is automatically created and filled with zeros if necessary, up to size bytes. If the addr content, at return of Cglobals_get, is not NULL, you can safely fill this memory with any value, provided you does not exceed the size bytes length specified in your previous call to Cglobals_get. Because of applications that are not multi-threaded, the initial value of key has then an importance, that's why it is necessary to always declare it with an initial value of -1. Return code is -1 on error, 0 on success and not the first call for this key , 1 on success and it is the first call for this key. This allows to distinguish when Cglobals_get() initialize the memory with zeros (return code 1) and not (return code 0). Cglobals_getTid uses the third function address, getTid , given as an argument to Cglobals_init, and will return in Tid content the value returned by getTid. C__serrno, C__rfio_errno, C__Copterr, C__Coptind, C__Coptopt, C__Coptreset, C__Coptarg and C__h_errno are all the internal functions that return the address of the thread-specific memory hosting the value of the 'global' variables serrno, rfio_errno, Copterr, Coptind, Coptopt, Coptreset, Coptarg and h_errno, respectively. EXAMPLE
Any application can create its own instance of thread-specific global variable using Cglobals. You need only to use Cglobals_get. Here is how to proceed. /* * The following shows how to define and use a thread-specific * integer, my_var, inside your package */ #include <stdlib.h> #include <stdio.h> #include <Cglobals.h> /* Get Cglobals_get prototype */ static int my_key = -1; /* Our static key, integer, init value -1 */ #define my_var (*C__my_var()) static int my_var_static; /* If Cglobals_get error in order not to crash */ int *C__my_var() { int *var; /* Call Cglobals_get */ Cglobals_get(&my_key, (void **) &var, sizeof(int) ); /* If error, var will be NULL */ if (var == NULL) { fprintf(stderr,"Cglobals_get error0); return(&my_var_static); } return(var); } int main() { fprintf(stdout, "Current my_var value is: %d0, my_var); fprintf(stdout, "Set my_var value to: %d0, 12); my_var = 12; fprintf(stdout, "Current my_var value is: %d0, my_var); return(0); } The following example is the source of the test suite for Cglobals_get(): #include <Cthread_api.h> #include <stdlib.h> #include <stdio.h> #include <Cglobals.h> /* Get Cglobals_get prototype */ #include <serrno.h> static int my_key = -1; /* Our static key, integer, init value -1 */ #define my_var (*C__my_var()) static int my_var_static; /* If Cglobals_get error in order not to crash */ void *doit _PROTO((void *)); int doit_v = 0; #define NTHREAD 100 int *C__my_var() { int *var; /* Call Cglobals_get */ switch (Cglobals_get(&my_key, (void **) &var, sizeof(int) )) { case -1: fprintf(stderr,"[%d] Cglobals_get error0, Cthread_self()); break; case 0: fprintf(stderr,"[%d] Cglobals_get OK0, Cthread_self()); break; case 1: fprintf(stderr,"[%d] Cglobals_get OK and first call0, Cthread_self()); break; default: fprintf(stderr,"[%d] Cglobals_get unknown return code0, Cthread_self()); break; } /* If error, var will be NULL */ if (var == NULL) { fprintf(stderr,"[%d] Cglobals_get error : RETURN static ADDRESS!!!!!!!!!!!!0, Cthread_self()); return(&my_var_static); } return(var); } int main() { int i; fprintf(stdout, "[%d] ---> Before any Cthread call0, -1); fprintf(stdout, "[%d] Current my_var value is: %d0, -1, my_var); fprintf(stdout, "[%d] Set my_var value to: %d0, -1, 12); my_var = 12; fprintf(stdout, "[%d] Current my_var value is: %d0, -1, my_var); fprintf(stdout, "[%d] Testing consistency0, -1); if (my_var != 12) { fprintf(stdout, "[%d] Cglobals_get worked ok0, -1); exit(1); } sleep(1); for (i = 0; i < NTHREAD; i++) { Cthread_create(&doit, &doit_v); doit_v++; } fprintf(stdout, "[%d] ---> After all Cthread_create calls0, -1); fprintf(stdout, "[%d] Current my_var value is: %d0, -1, my_var); fprintf(stdout, "[%d] Set my_var value to: %d0, -1, NTHREAD * 10000 + 12); my_var = NTHREAD * 10000 + 12; fprintf(stdout, "[%d] Current my_var value is: %d0, -1, my_var); fprintf(stdout, "[%d] Testing consistency0, -1); if (my_var != (NTHREAD * 10000 + 12)) { fprintf(stdout, "[%d] Cglobals_get worked ok0, -1); exit(1); } sleep(1); exit(0); } void *doit(arg) void *arg; { int Tid; int doit = * (int *) arg; Cglobals_getTid(&Tid); my_var = (Tid + 1) * 100 + 12; fprintf(stdout, "[%d] my_var value is: %d (should be %d)0, Cthread_self(), my_var, (Tid + 1) * 100 + 12); fprintf(stdout, "[%d] second call -- my_var value is: %d (should be %d)0, Cthread_self(), my_var, (Tid + 1) * 100 + 12); fprintf(stdout, "[%d] Testing consistency0, Cthread_self()); if (my_var != ((Tid + 1) * 100 + 12)) { fprintf(stdout, "[%d] !!!!!!!!! ERROR !!!!!!!!!0, Cthread_self()); exit(1); } else { fprintf(stdout, "[%d] Cglobals_get worked ok0, Cthread_self()); } return(0); } SEE ALSO
Cthread(3), serrno(3), Cgetopt(3) AUTHOR
LCG Grid Deployment Team LCG
$Date: 2010-04-05 09:51:26 +0200 (Mon, 05 Apr 2010) $ CGLOBALS(3)
All times are GMT -4. The time now is 05:40 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy