tags:

views:

397

answers:

3

In Linux and other UNIX-like operating systems, it is possible for two (or more) processes to share an Internet socket. Assuming there is no parent-child relationship between the processes, is there any way to tell what process originally created a socket?

Clarification: I need to determine this from "outside" the processes using the /proc filesystem or similar. I can't modify the code of the processes. I can already tell what processes are sharing sockets by reading /proc/<pid>/fd, but that doesn't tell me what process originally created them.

A: 

I don't know about using sendmsg() to "send" a socket from one process to another.

I do know that the bind() system-call will return EADDRINUSE if a second process attempts to use the same port.

Steve Emmerson
A: 

You can likely find the shared sockets by parsing /proc/net/tcp (and similar "files" for other protocols). There's some docs on /proc/net/tcp here.

You would need to find the socket (perhaps by its IP addresses/port numbers ?) and parse out the inode number. Once you have the inode, you can search through all of /proc/*/fd/* , calling stat for every link and inspect the st_ino member of struct stat until you find a match.

The inode number should match between the 2 processes, so when you've gone through all /proc/*/fd/* you should have found them both.

If what you do know is the process id and socket fd of the first, you might not need to go through /proc/net/tcp, all you need to do is stat the /proc/<pid>/fd/<fd> and search the rest of /proc/*/fd/* for a matching inode. You'd need /proc/net/tcp if you want to fetch the ip addresses/port number though - which you can find if you know the inode number

nos
Maybe I didn't explain myself well. I already know how to find out which processes are sharing sockets. I do that using exactly the method you described. But this doesn't help me determine which process owned the socket originally. Perhaps I need to make a guess based on the age of each process.
Rob H
It would be very helpful if you updated your question to state what you are looking for, and that you are doing this from outside any of the programs involved. There is however no direct information on the original owner or creator anywhere. The closest thing you will get is calling `lstat` on the links in /proc/pid/fd/fd and guess that the oldest timestamp(ctime likely) was the original creator.
nos
Updated the question to clarify.
Rob H
A: 

doesn't 'lsof -Ua' help?

Cypher