Tono
Tono

Reputation: 39

Sending size of buffer through pipe from process to process

I have created two child processes with a pipe connection between them.

Code in process A:

char *buf;
size_t size;

buf = "some string";
size = strlen(buf);
printf("size in process A:%zu\n", size);
write(pfds[3][1], &size, sizeof (size_t));
write(pfds[3][1], buf, sizeof (buf));


buf="other string";
size = strlen(buf);
printf("size in process A:%zu\n", size);
write(pfds[3][1], &size, sizeof (size_t));
write(pfds[3][1], buf, sizeof (buf));

Code in process B:

size_t size;
/*read in size from Process A*/
read(pfds[3][0], &size, sizeof (size_t));
printf("READ size in process B: %zu\n", size);

/*allocate memory space for the line*/
char *buf = malloc(size);

/*read in line from process A*/
read(pfds[3][0], buf, size);
printf("READ buf in process B: %s.\n", buf);

/*read in size from readProcess*/
read(pfds[3][0], &size, sizeof (size_t));
printf("READ size in process B:%zu\n", size);

/*free the allocated memory*/
free(buf);

The output looks like this:

size in process A:11
size in process A:12
READ size in process B: 11
READ buf in process B: some
                            .
READ size in process B:101

I want to use the size to control a while loop to continuously send lines from A to B, until the size becomes 0. But what am I doing wrong? The size is right the first time it is sent, but not the second time.

Upvotes: 1

Views: 530

Answers (1)

Raam
Raam

Reputation: 10886

sizof(buf) will return 4, the size of a pointer, What you need is strlen(buf) so

write(pfds[3][1], buf, sizeof (buf));

should be

write(pfds[3][1], buf, strlen(buf));

Upvotes: 4

Related Questions