1

我创建了两个子进程,它们之间有管道连接。

进程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));

进程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);

输出如下所示:

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

我想用大小来控制一个while循环,不断地将行从A发送到B,直到大小变为0。但是我做错了什么?第一次发送时大小正确,但第二次发送时不正确。

4

1 回答 1

4

sizof(buf) 将返回 4,一个指针的大小,你需要的是 strlen(buf) 所以

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

应该

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

于 2012-05-27T08:52:52.373 回答