I have been running a C program which connects to a Redis database every once in a while. After running the program for a few hours it was displaying "Cannot create socket: too many files open". I'm pretty sure that I'm closing the connection every time after I'm done with the logic part at the database. So I wanted to know if there is any way to know how many sockets have been created by a C program, while it is running? I'm using Ubuntu 16.04.
You did not specify an operating system, and
/proc/*/fd/ does not exist on all operating systems.
You actually need to list all of the currently open file descriptors for the process, from which you can determine what is actually being leaked. It is not necessarily a socket file descriptor that is being leaked.
On FreeBSD, NetBSD, OpenBSD …
… and their various derivatives (e.g. TrueOS, DragonFly BSD).
fstat command with the
-p option and the relevant process ID:
fstat -p 718
fstat. NetBSD General Commands Manual. 2013-12-15.
procfiles command similarly, with the
-n option to print names:
procfiles -n 6679
procfiles. AIX 7.2. IBM Knowledge Centre.
On OpenSolaris …
… and thus on Illumos, Schillix, et al.
pfiles. User Commands. SunOS 10.5 Manual. 2008-12-10.
lsof command similarly:
lsof -p 41467
In my C++ programs, a simple class that owns a file descriptor and closes it in its destructor works wonders. Unfortunately, you'll have to resort to GNU-specific language extensions (i.e.
__attribute__(__cleanup__)) to get that in C programs.
You can of course go further with other tools. With DTrace and a suitable script, you can monitor the process as it opens and closes file descriptors. (You can do this with
strace, too; although the their mechanisms for selecting subsets of the system calls made are either fairly basic or nonexistent. You can also do this with a debugger and some suitable breakpoints.)
At a system level at does not better what language the program is written in.
/proc/«pid»/fd will tell you total number of file descriptors, that the process has open (not just sockets), but will be a close approximation. Maybe some one else can tell you for sockets.
There is also
strace you can use this to trace system calls that your process makes.
strace «my-program» «program args…»
in the program
Add some logging: printf when you open and close a socket, to a logfile.