【问题标题】:Sending structure through pipe without losing data通过管道发送结构而不丢失数据
【发布时间】:2015-04-22 15:41:03
【问题描述】:

我有这个结构:

typedef struct {
    int pid;
    char arg[100];
    int nr;
} Str;

代码是这样的:

int main() {
    int c2p[2];
    pipe(c2p);
    int f = fork();

    if (f == 0) { // child
        Str s;
        s.pid = 1234;
        strcpy(s.arg, "abcdef");
        s.nr = 1;

        close(c2p[0]);
        write(c2p[1], &s, sizeof(Str*));
        close(c2p[1]);
        exit(0);
    }

    // parent
    wait(0);
    close(c2p[1]);
    Str s;
    read(c2p[0], &s, sizeof(Str*));
    printf("pid: %d nr: %d arg: %s", s.pid, s.nr, s.arg);
    close(c2p[0]);
    return 0;
}

输出是这样的:

pid: 1234 nr: 0 arg: abc$%^&

pid 总是正确的,nr 总是 0 并且 arg 的前几个字符是正确的,然后是一些随机字符。

我想在子进程中创建一个结构体,然后通过管道将结构体发送给父进程。

我怎样才能通过管道正确发送这个结构?

【问题讨论】:

  • 这个sizeof(Str*) 看起来很糟糕。
  • 您的代码遗漏了相关的#includes。

标签: c struct process pipe


【解决方案1】:
write(c2p[1], &s, sizeof(Str*));

不对。那将只写入指针大小的字节数。应该是

write(c2p[1], &s, sizeof(Str)); // -- without the `*`. 

同样,你需要使用:

read(c2p[0], &s, sizeof(Str));  // -- without the `*`. 

【讨论】:

  • 为什么不只是sizeof s?如果s 的类型发生变化,这会减少错误。
  • 我认为 OP 没有发布真正的代码,因为 sizeof(Str *) 甚至不应该编译。
  • @PaulR, sizeof(Str *) 是一个有效的表达式。它评估为指针的大小。
  • @RSahu:真的吗? Str 是一个结构 - 为什么 Str * 是一个指针?
  • @RSahu:谢谢 - 我现在明白了 - 显然我暂时遭受了 Coders' Block 的痛苦。 ;-)
猜你喜欢
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 2012-12-16
  • 2021-06-27
相关资源
最近更新 更多