c - Sending structure through pipe without losing data -
i have structure:
typedef struct { int pid; char arg[100]; int nr; } str;
the code this:
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; }
the output this:
pid: 1234 nr: 0 arg: abc$%^&
pid right, nr 0 , fist few characters arg right followed random characters.
i want create structure in child process , send structure parent process through pipe.
how can send correctly structure through pipe?
write(c2p[1], &s, sizeof(str*));
is not right. write number of bytes size of pointer. should be
write(c2p[1], &s, sizeof(str)); // -- without `*`.
similarly, need use:
read(c2p[0], &s, sizeof(str)); // -- without `*`.
Comments
Post a Comment