SSC
SSC

Reputation: 1331

Passing a structure through unix domain socket

I am working on a project that is using Unix domain socket (AF_UNIX) as a choice of IPC between different processes.

When I want to pass a data structure from one process to another, do I need to do serialization on the data structure as mentioned in this question (Passing a structure through Sockets in C)?

Since these processes are compiled with same compiler and running on the same machine, there should be no endianness , nor different padding issue. So I am not sure if serialization is necessary.

Upvotes: 3

Views: 2081

Answers (2)

Jasen
Jasen

Reputation: 12412

You need only ensure that the received structure is intelligible.

If the structure is composed of self-contained types then no processing is required, you can just call write() or send() to push the data into the socket.

Serialisation is needed where the structure is not self-contained ( eg if it contains pointers, or platform-specific data types)

If there a chance that the two processes could have different bit-ness (eg 32 bit vis 64 bit) or different endian-ness you'll want to take care that the struct is well-defined such that it comes out with the same binary representation in both forms.

Upvotes: 3

Art
Art

Reputation: 20392

Serialization is not necessary in this case. Every operating system and CPU architecture combination will have a quite well defined ABI which says how structs and such are laid out in memory. This severely limits the compiler in how much it is allowed to change things around and for a good reason - change the ABI and all precompiled libraries stop working. So if you compile stuff with the same compiler targeting the same architecture the in-memory layout of structs will be the same.

To be sure, just remember to rebuild both sides on major operating system updates in case the ABI changes (which it never does, but it could happen some day).

Upvotes: 1

Related Questions