문제

#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.

도움이 되었습니까?

해결책 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...........

다른 팁

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top