Hi all,
I'm currently developping an app in C++ that has to transmit over CAN bus.
It runs on a SBC9261 board, under Linux 2.6.24.
Two pthreads are working for this : the first checks whether a CAN-frame was received. If so, it launches a second thread that has to handle the frame. This way, I'm able to receive frames while handling others (this is sometimes necessary, as some frame-processing needs informations from other CAN-devices).
Here is the code (a bit simplified) of the first thread's routine (the one which receive the frames) :
Code:
void *canRead(void *arg) {
struct can_frame frameRecv;
unsigned int i;
pthread_attr_t attr;
pthread_t threadHandler;
// P. thread attribute
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
while(1) {
// Init frame
memset(&frameRecv, 0, sizeof(struct can_frame));
// Read from CAN
read(canDevice, &frameRecv, sizeof(struct can_frame));
// Threading to be able to receive while handling requests
// pthread_create() prototype : int pthread_create(pthread *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg_of_routine);
if (pthread_create(&threadHandler, &attr, canHandler, &frameRecv)) {
perror("pthread_create");
exit(-1);
}
// Sleep for a while
usleep(50*1000);
}
}
canHandler is the routine that handles the CAN-frame. There is no infinite loop in it, and it could take like 3 secs to end, in the worst case.
This works fine, at least the first 15 minutes, because here is the problem :
The canHandler threads seem to remain in memory after they terminate, as it decreases until the program crashes, throwing a Segmentation Fault.
I spotted this behavior with the
top command. If I remove the
pthread_create line, the app can run all night without exceeding 17% of memory.
I took a look at the
pthread_create manual and one gives a
usage example where freeing memory is done.
The interessant part is :
Code:
void *res;
/*Creating different threads, doing stuff here...*/
pthread_join(<whatever_thread>, &res);
free(res); /* Free memory allocated by thread */
But I can't use it that way, as I have no thread to join...
But does someone know how I could initialize that res pointer or use that free() function to stop those memory leaks ?
Thank you for your help or suggestions !