Question

#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);
    }
}

The problem is the elements in the structure are not appearing at the read end, could anyone please check on this. we can pass a string to a pipe, but I need to pass the bunch of integers to the pipe.

Was it helpful?

Solution 2

#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++);
    }
    }
 }

try this code.......... here make sure you use waitpid() instead of sleep so that parent process waits for child procees to terminate or else you will get inappropriate response...........

OTHER TIPS

The bytes get read at the receiving end, but you try to print binary data as a string.

Treat the read bytes as struct msg instead:

else
{
     struct msg received; 
     read(p[0], &received, sizeof(received));
     printf("%d, %d, %d\n", received.pid, received.giffs, received.curr);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top