How socket file actually works?
Asked Answered
C

3

5

I'm currently interesting in UNIX system.

For IPC(Interprocess Communication), UNIX uses a file named socket. I understand it works like server-client model, write-end and read-end uses socket file to communicate each other.

But I wonder how socket internally works. Each process designate a socket file(maybe with inode), then write and read on it? If it's true, can I watch raw data(or encapsulated data) if I'm watching this socket file?

One more, socket file has a format? For example, some application socket file like mysql.sock and docker.sock, they have their own format?

Clyde answered 20/3, 2022 at 6:38 Comment(0)
S
14

The proper name for unix sockets is Unix Domain Sockets, because they all reside within one computer. In a sense, sockets are a network that is entirely contained within the kernel; rather than using network interfaces to send data, that same data can be sent directly between programs

Despite creating files on disk, Unix sockets don’t actually write the data they send to the disk, as that would be far too slow. Instead, all the data is retained within kernel memory; the only point of the socket file is to maintain a reference to the socket, and to give it filesystem permissions to control access. For example, MySQL’s socket is usually at:

/var/lib/mysql/mysql.sock

This file doesn’t contain anything, and you shouldn’t modify it directly, except for the permissions where applicable. It’s just a name.

Selfdrive answered 20/3, 2022 at 6:38 Comment(0)
O
1

Sockets don't contain anything. They are kind of like a "hole", that applications have access to for reading and writing.

Unix sockets create less overhead and communication is faster, than by localhost IP sockets.

Using sockets is a more efficient means of getting the job done, but generally only used by heavy I/O apps (like mailer daemons).

Outlet answered 22/3, 2022 at 3:53 Comment(0)
A
0

Internally Unix sockets transfer data over kernel buffers. They represented as inode, so you see them and work as regular files. You can watch data, but you probably will erase it from socket (buffers usually clear after reading).

Socket not a file, it is a inode. UNIX like everything be a file, very usefull.

Ahmednagar answered 1/11 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.