通过管道从进程到进程发送缓冲区大小

时间:2012-05-27 08:46:13

标签: c process pipe

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

流程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.但是我做错了什么?大小在第一次发送时是正确的,但不是第二次。

1 个答案:

答案 0 :(得分:4)

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

  

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

应该是

  

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