简体   繁体   English

通过unix域套接字传递结构

[英]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. 我正在开发一个使用Unix域套接字(AF_UNIX)作为不同进程之间的IPC选择的项目。

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 )? 当我想将数据结构从一个进程传递到另一个进程时,是否需要对数据结构进行序列化,如本问题中所述( 通过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. 所以我不确定序列化是否必要。

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. 如果结构由自包含类型组成,则不需要处理,只需调用write()或send()将数据推送到套接字即可。

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. 如果两个进程有可能具有不同的位(例如32位可见64位)或不同的字节序,那么你需要注意结构是否定义良好,以便它具有相同的二进制两种形式的代表。

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. 每个操作系统和CPU架构组合都有一个非常明确的ABI,它说明了结构等在内存中的布局。 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. 这严重限制了编译器允许更改周围事物的数量,并且有充分理由 - 更改ABI并且所有预编译库都停止工作。 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). 可以肯定的是,只要记住在主要操作系统更新时重建双方,以防ABI发生变化(从未发生过变化,但有一天可能会发生)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM