gpt4 book ai didi

c - 通过管道从一个进程发送到另一个进程的缓冲区大小

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:09 24 4
gpt4 key购买 nike

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

进程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。但是我做错了什么?第一次发送大小合适,第二次发送就不行了。

最佳答案

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

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

应该是

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

关于c - 通过管道从一个进程发送到另一个进程的缓冲区大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10772747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com