通过管道发送结构而不丢失数据 [英] Sending structure through pipe without losing data

查看:85
本文介绍了通过管道发送结构而不丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

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中的第一个字符是正确的,后面跟着一些随机字符.

pid is always right, nr is always 0 and the fist few characters from arg are right followed by some random characters.

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

I want to create a structure in the child process and then send the structure to the parent process through pipe.

如何通过管道正确发送此结构?

How can I send correctly this structure through pipe?

推荐答案

write(c2p[1], &s, sizeof(Str*));

不正确.那只会写一个指针大小的字节数.应该是

is not right. That would write only the number of bytes the size of a pointer. It should be

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

类似地,您需要使用:

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

这篇关于通过管道发送结构而不丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆