如何将结构中的元素传递给未命名的管道?

时间:2014-04-08 10:43:28

标签: c ipc

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>  

struct msg
{
    int pid;
    int giffs;
    int curr; 
};

main()
{
    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    char inbuff[sizeof(send)];
    char *q;
    pipe(p);
    pid = fork();
    if(pid > 0)
    {
         write(p[1], (char *)&send, sizeof(send));
         printf("%ld \n", sizeof(send));
    }
    else
    { 
         read(p[0], inbuff, sizeof(send));
         printf("%s\n", inbuff);
    }
}

问题是结构中的元素没有出现在读取端, 有谁可以请检查这个。我们可以将一个字符串传递给一个管道,但我需要将一堆整数传递给管道。

2 个答案:

答案 0 :(得分:1)

在接收端读取字节,但您尝试将二进制数据打印为字符串。

将读取的字节视为struct msg

else
{
     struct msg received; 
     read(p[0], &received, sizeof(received));
     printf("%d, %d, %d\n", received.pid, received.giffs, received.curr);
}

答案 1 :(得分:0)

#include <stdio.h>
#include <unistd.h>
 #include <fcntl.h>  
struct msg {
    int pid;
        int giffs;
        int curr;
};

main()
{

    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    int *inbuff;
    char *q;
    pipe(p);
    pid= fork();
    if(pid > 0) {
            write(p[1], (char *)&send, sizeof(send));
            printf("%ld \n", sizeof(send));
            sleep(1);
    } else { 
        read(p[0],(char *) inbuff, sizeof(send));
    for (i=0;i<sizeof(send)/sizeof(int);i++){
            printf("%d\n", *inbuff++);
    }
    }
 }

试试这段代码.......... 这里确保你使用waitpid()而不是sleep,以便父进程等待子进程终止,否则你会得到不适当的响应............