Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an open file is a socket or a pipe?

I am trying to find what member(s) of the struct fdtable or struct file will let me determine whether or not an open file is a socket or a pipe.

the only path I can seem to find is:

struct file f ....;
f.path->mnt->mnt_devname

This returns the device name at the mountpoint, all sockets/pipes apparently belong to sockfs or pipefs respectively.

Is there a faster way to check to see if an open file is a socket or pipe using a different member of the struct file or fdtable?

Note: I am using the kernel definitions from 2.6.24

like image 684
Hunter McMillen Avatar asked Mar 30 '12 18:03

Hunter McMillen


People also ask

What is the difference between an open file and a socket?

The main difference between sockets and files is that the operating system binds file descriptors to a file or device when the open() call creates the file descriptor.

Is socket a file?

A socket is a special file used for inter-process communication, which enables communication between two processes. In addition to sending data, processes can send file descriptors across a Unix domain socket connection using the sendmsg() and recvmsg() system calls.

How do you test whether a socket is ready to be read or written?

To test whether any sockets are ready for writing, initialize the fdset bit set in writelist with either FD_ZERO() or memset(), if dynamically allocated, and use FD_SET() for each socket to test. A message queue is ready for reading when any time it has a message on it.

Where are socket files stored?

They are to be stored in /run/ according to the Filesystem Hierarchy Standard (FHS). System programs that maintain transient UNIX-domain sockets must place them in this directory or an appropriate subdirectory as outlined above.


1 Answers

There are special macro definitions at linux/stat.h that checks inode->i_mode:

  #define S_ISLNK(m)      (((m) & S_IFMT) == S_IFLNK)
  #define S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)
  #define S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)
  #define S_ISCHR(m)      (((m) & S_IFMT) == S_IFCHR)
  #define S_ISBLK(m)      (((m) & S_IFMT) == S_IFBLK)
  #define S_ISFIFO(m)     (((m) & S_IFMT) == S_IFIFO)
  #define S_ISSOCK(m)     (((m) & S_IFMT) == S_IFSOCK)

It seems that you'll need to use 2 of them - S_ISFIFO and S_ISSOCK in a such way:

if (S_ISFIFO(file->f_path.dentry->d_inode->i_mode)) {...}
if (S_ISSOCK(file->f_path.dentry->d_inode->i_mode)) {...}
like image 61
Ilya Matveychikov Avatar answered Oct 08 '22 01:10

Ilya Matveychikov