Reputation: 61
I have this structure:
typedef struct {
int pid;
char arg[100];
int nr;
} Str;
The code is something like 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 is something like this:
pid: 1234 nr: 0 arg: abc$%^&
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?
Upvotes: 1
Views: 3530
Reputation: 206637
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 `*`.
Similarly, you need to use:
read(c2p[0], &s, sizeof(Str)); // -- without the `*`.
Upvotes: 3