我如何序列化一个对象而不会有任何数据损坏的风险?

How could I serialize an Object without any risk of data corruption ?

我想连载一个像这样的基本 class :

class ProcessData
{
  public:
    ProcessData();
    ProcessData(int processNumber, int threadStatus);
    ~ProcessData();
    int getProcessNumber() const;
    void setProcessNumber(int processNumber);
    int getThreadStatus() const;
    void setThreadStatus(int threadStatus);
  private:
    int _processNumber;
    int _threadStatus;
};

并将其写入命名管道。 我使用命名管道是因为我需要我的子进程向我的主进程发送数据。

我的主进程将读取这个命名管道并取回我的对象​​。

问题是很多进程可以写入命名管道,这可能会导致问题。 要连载这个 class 我想我可以做这样的事情:

write(namePipeFileDesriptor, &processDataClass, sizeof(processDataClass)));

您认为这行得通吗,或者除了 boost::serialization 之外还有其他选择吗?

我建议使用 google::protobuf 库进行序列化和反序列化。高效快捷。

对于您的情况,您只需创建一个 .proto 文件

// File.proto
message ProcessData
{
  int32 _processNumber;
  int32 _threadStatus;
}

protoc编译器编译后,你会得到"File.pb.h"和"File.pb.cpp",你必须将它们添加到你自己的项目中。而已。现在您可以使用这些源文件中提供的各种方法简单地序列化和反序列化所需的数据。

另一个额外的好处是,同样的 "File.proto" 可以用于其他语言,如 Go、Phython、Java、C# 等,因为消息在语言中是 [反] 序列化的独立方式

只要reader和writer进程运行在同一台电脑上,为同一个目标编译,具有相同的对齐规则,并且要发送的数据是POD(或者可以是被视为 POD),您可以按原样传输数据,就像您建议的那样,并避免使用序列化库。

现在,我猜你关心的是 write/read 操作的原子性,无论你使用什么序列化技术,考虑到多个写入进程可以写入管道。

假设您的 OS 是 POSIX 兼容的,只要发送的数据大小不超过管道缓冲区大小,您就可以将任何写操作视为原子操作(即:无数据交错)。

Standard 状态:

Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.

PIPE_BUF 的值 OS 相关,但应大于 512 字节。 (linux OSes 是 4096 字节。)因此,对于小数据,应该没有问题。