I have to write a SNMP module which monitor a certain server application that I have written too. The problem is that I have to know if this application is running and I should be able to kill it whenever I can.
I know the port where the application is listening (reading the application configuration file) and I can try to bind this port to a socket in order to know if it is (or isn’t) being used by my application or another which is enough for my module. Here is the code:
int
get_server_status()
{
struct sockaddr_in local;
int port,sockfd;
if (parse_config_file(&port,NULL,CONFIG_FILE_PATH) == -1)
return -1; //Error
if ((sockfd = socket ( AF_INET, SOCK_STREAM, 0 )) < 0)
return -1; //Error
local.sin_family = AF_INET;
local.sin_port = htons ( port );
local.sin_addr.s_addr = inet_addr ("127.0.0.1");
if (bind(sockfd, (struct sockaddr *) &local, sizeof (local) ) < 0 ){
if(errno == EADDRINUSE)
return 1; //Port being used
else
return -1; //Error
}else{
close(sockfd);
return 0; //Port not being used
}
}
The problem comes when I need to kill the application, I don’t know neither its PID nor how to get it. I can get is using netstat -tln <port>but I don’t know how to do it programmatically. Any ideas??
Like
netstat, you should read/proc/net/tcp.Interpreting it:
local_address, is the IP and port.00000000:0050would be HTTP (the port number is in hex).st, is the state.AisTCP_LISTEN.inodeis the inode number (decimal this time)./proc/pid/fd/contains an entry for each open file descriptor.ls -lfor socket descriptors shows that it’s a link tosocket:[nnnnnn]. The numbernnnnnnshould match the inode number from/proc/net/tcp.This makes finding the process quite tiresome, but possible.
Finding the right line in
/proc/net/tcpisn’t difficult, and then you can get the inode number.Finding the process requires you to scan all processes, looking for one which refers this inode number. I know no better way.