There is a line in my code where I am doing this-
int sockDesc = socket(AF_INET, SOCK_DGRAM, 0);
Earlier it was working like a charm, but then suddenly one day the function returned something less than zero. So I examined standard error and found Too many open files
.
I realised that what I have done is, exited the program using ctrl + c
many times. so may be the sockets are somehow still open and I need to do something about it (apart from writing a signal handler of course), like - increasing some limits in the /etc/sysctl.conf
file and all.
But that is wrong right? When I exited the program, won't linux automatically clean up after me ?
Just to confirm this is not some issue caused by stuff let opened by me all over the RAM, I rebooted- Still the same error !
What is going on here ? But wait a minute. I had already closed my program and restarted it. Why must I get such an error in my system? What is a way to correctly diagnose this? Is this really about sockets or any other type of open file descriptors? What should be my next step to solve this issue?
EDIT 1:
I ran another small program:
int main()
{
int sd;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd < 0)
{
perror("Opening datagram socket error");
return 1;
}
else
{
printf("Opening datagram socket....OK.\n");
}
close(sd);
return true;
}
Which ran with no issues. Now I really do not understand what could be the issue. The exact same code is not working when it is running from my actual code base.
Also, the output of lsof
has only 236 lines in it for my user, which means that I a well below the soft limit of 1024.
EDIT 2
Here is some of the code explanation to explain how I am doing things
There is a main file that creates multiple threads, each one being a network connection to a multicast stream. The beginning of each such thread is the line int sockDesc = socket(AF_INET, SOCK_DGRAM, 0);
. This is where it fails. For some reason it says "too many open files" and the socket is not created.