473,779 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threads don't seem to be cleaned up

jlm699
314 Contributor
Greetings all,

I have this server (running on Linux 2.6.17-gentoo-r9) that I've been tinkering with and I attempted to do a multi-threaded model to accept multiple connections, however I found that it was leaving zombie processes and not cleaning up after itself at all. The main thread was doing a waitpid((pid_t)-1, Null, WNOHANG) and keeping track of the number of clients it created/cleaned up. Since that did not work as I had expected I decided to try and allow only a single connection (ie, wait(NULL) causing the main thread to not listen for client connections until it cleaned up its child). While this works great and appears to clean up children when monitoring ps, when I watch 'top' it seems that used memory just constantly increases once the first client thread is spawned. After it is closed the used memory goes down a little, but then ever-so-slowly increases. If I remove the client threading all together the used memory does not fluctuate. Could somebody please peruse this threading model code I have posted below and tell me if I'm doing something blatently dumb?! I would greatly appreciate it!

Expand|Select|Wrap|Line Numbers
  1. int main(char argc, char *argv[])
  2. {
  3.     pid_t    pid;
  4.     pid_t    process_id;
  5.     struct    sigaction sa;
  6.     int    error;
  7.     int    sockfd;
  8.     int    ss_fd;
  9.     char    response[MAX_MSG_BUFF_SIZE];
  10.  
  11.  
  12.     sprintf(VersionString, "Daemon v %d.%d.%d", MajorVersion, 
  13.         MinorVersion, PatchVersion);                
  14.  
  15.     /* Spawn the daemon */
  16.     pid = fork();
  17.  
  18.     if (pid < 0) {
  19.         printf("Failed PID #0\n");
  20.         exit(EXIT_FAILURE);
  21.     }
  22.     else if (pid > 0) {
  23.         exit(EXIT_SUCCESS);
  24.     }
  25.  
  26.     sid = setsid();
  27.     if (sid < 0) {
  28.         printf("Failed SID\n");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.  
  32.     /* Set up and install handler for signal SIGTERM */
  33.     memset(&sa, 0, sizeof(sa));
  34.     sa.sa_handler = &sigterm_handler;
  35.     sigemptyset(&sa.sa_mask);
  36.     sa.sa_flags = 0;
  37.     sigaction(SIGTERM, &sa, NULL);
  38.  
  39.     /* Set up and install handler for signal SIGINT */
  40.     memset(&sa, 0, sizeof(sa));
  41.     sa.sa_handler = &sigint_handler;
  42.     sigemptyset(&sa.sa_mask);
  43.     sa.sa_flags = 0;
  44.     sigaction(SIGINT, &sa, NULL);
  45.  
  46.     ss_fd = ds_open_server(DSTREAM_PORT);
  47.     if (ss_fd == -1) {
  48.         printf("ds_open_server socket error\n");
  49.         exit(1);
  50.     }
  51.  
  52.     while (!quit_daemon)
  53.     {
  54.         sockfd = 0;
  55.         if ((sockfd = ds_listen_for_client(ss_fd, BACKLOG)) > 0)
  56.         {
  57.             if (client_cnt > 5)
  58.             {
  59.                 strcpy(response, "MAX_CLIENTS");
  60.                 ds_send(sockfd, response, strlen(response));
  61.                 ds_close(sockfd);
  62.                 sleep(SLEEP_TIME);
  63.             }
  64.             else
  65.             {
  66.                 pid = fork();
  67.                 if (pid > 0)
  68.                 {
  69.                     client_cnt++;
  70.  
  71.                     while (client_cnt)
  72.                     {
  73.                         process_id = wait(NULL);
  74.                         /* This was causing zombie processes */
  75.                         //process_id = waitpid((pid_t) -1, NULL, WNOHANG); /* non-blocking wait */
  76.                         if (process_id < 0)
  77.                         {    /* waitpid error */
  78.                             perror("waitpid");
  79.                         }
  80.                         else if (process_id == 0)
  81.                         {    /* no zombies to wait on */
  82.                             break;
  83.                         }
  84.                         else
  85.                         {
  86.                             client_cnt--;
  87.                             //printf("Stopped child process %d\n", process_id);
  88.                         }
  89.                     }
  90.                 }
  91.                 else
  92.                 {
  93.                     if ((error = StartDataStreamer(sockfd)))
  94.                     {
  95.                         printf("Exiting with error = %d\n", error);
  96.                         StopDataStreamer();
  97.  
  98.                         exit(EXIT_FAILURE);
  99.                     }
  100.                     else
  101.                     {
  102.                         // printf("Datastreamer started successfully:  %d\n", sockfd);
  103.                         while (!quit_client)
  104.                         {
  105.                             // printf("sleeping client %d\n",sockfd);
  106.                             sleep(SLEEP_TIME);
  107.                         }
  108.                         exit(EXIT_SUCCESS);
  109.                     }    // end else
  110.                 }    // end else    
  111.             }    // end else
  112.         }    // end if
  113.     }    // end while
  114.  
  115.     ds_close_server(ss_fd);
  116.     exit(EXIT_SUCCESS);
  117. }    // end main
And by the way, the ds_* functions are just wrappers I made to simplify the amount of typing for sending/receiving/opening connections etc. And then StartDataStream er is the actual code that does the work of transferring data back and forth from my other computer. StopDataStreame r just shuts everything down (raising quit_daemon). I don't see why this would cause a memory leak, and also if anybody has any idea why the original waitpid method was leaving zombies I'd love to hear your thoughts.

Thanks in advance!

James
Aug 9 '07 #1
0 1309

Sign in to post your reply or Sign up for a free account.

Similar topics

11
3643
by: Rohit | last post by:
Hi, Threads in the .NET Framework 1.1 (and possibly in 1.0 also) leak "Event" handles, by Event handles I mean Win32 Event handles which can be monitored using the ProcessExplorer from www.sysinternals.com, or even simply look at the Handle count in the good old windows TaskManager. To demonstrate the problem, all I did was created a basic Win Forms application and with Main implemented as:
28
1885
by: Dennis Owens | last post by:
I am trying to run a thread off of a form, and every once in a while the thread will raise an event for the form to read. When the form gets the event, the form will place the event into a dataset and display it on a datagrid that is on the form. The problem is that the thread will slowly take over all of the processor time. After about 8 events, the form will not even respond anymore. Here is the guts of my test code // Class and event for...
2
1518
by: Jagadish | last post by:
Hi, My application requires to create a few threads on the occurance of an event E1 and the same threads need to be aborted on the occurance of another event E2. Iam not using .Net thread pool threads. Iam using system threads by using Thread objects and delegates. Threads are aborted by making an explicit call to Thread.Abort(). Occurance of events E1 and E2 are not under the control of my application. My application runs stable for a...
8
12949
by: Martin Maat | last post by:
I am puzzled. I have this object that uses a thread. The thread is encapsulated by the object, the object has Start and Stop methods to enable the client to start or stop the thread. I found that the object will not be garbage collected while the thread is running. Fair enough, the documented explanation is that the GC compresses objects on the heap and needs to update references, the references will be invalid for a couple of moments...
15
2609
by: Bryce K. Nielsen | last post by:
I have an object that starts a thread to do a "process". One of the steps inside this thread launches 12 other threads via a Delegate.BeginInvoke to process. After these 12 threads are launched, the main thread waits. At the completion of each subthread, the mainthread checks all 12 thread objects to see if they are done. If they are, raise an event that says we're done. So, it's kinda like this: ProcessThread - Creates a ProcessObject
7
1610
by: gel | last post by:
Hi all I am attempting to understand threads to use in a network app which I am writing. The part that I am going to use threads on is run on the clients/workstations. I will monitor all starting and ending processes. Below is what I have been doing. It looks like only the first thread is starting. Can someone explain a basic example of how threads work and are implemented, what is better to use threading or thread module, and what am...
35
4043
by: Carl J. Van Arsdall | last post by:
Alright, based a on discussion on this mailing list, I've started to wonder, why use threads vs processes. So, If I have a system that has a large area of shared memory, which would be better? I've been leaning towards threads, I'm going to say why. Processes seem fairly expensive from my research so far. Each fork copies the entire contents of memory into the new process. There's also a more expensive context switch between...
1
2099
by: sharekhan | last post by:
Hello, I have written a simple relay server. using pthreads. To handle multiple clients. Design wise its like this.. (my humble apologies if the post is too long) The thread design was borrowed from this article (http://www.codeproject.com/useritems/LikeJavaThreads.asp)
167
8351
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
0
9471
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10302
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10136
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9925
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8958
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6723
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3631
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.