You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ fork与pipe项目中write()/read()缓冲区类型不兼容问题

解决pipe中write/read调用的类型不匹配问题

错误原因

write()和read()是系统调用,它们的第二个参数要求传入内存缓冲区的地址(const void*对应write,void*对应read),用于指定数据要写入/读取的内存位置。你直接传递int类型的变量temptotal,本质是传递了变量的数值,而非内存地址,这就触发了类型不匹配的编译错误——int值无法转换为const void*类型的指针。

你之前的误解在于:const void*确实可以接收任意类型的指针(所有指针类型都能隐式转换为void*),但它接收的是指针,不是普通变量的值。

修复代码

只需要使用取地址运算符&获取temptotal的内存地址,传递给write和read即可:

写入pipe的代码:

int temptotal = 42; // 示例初始化值
write(fds[1], &temptotal, sizeof(int));

从pipe读取的代码:

int temptotal;
read(fds[0], &temptotal, sizeof(int));

额外注意事项

  • 确保pipe(fds)调用成功,已经正确初始化了管道的读写文件描述符。
  • 父子进程要及时关闭不需要的管道端:比如父进程只写的话,要关闭读端close(fds[0]);子进程只读的话,要关闭写端close(fds[1]),否则可能导致进程阻塞在read/write调用上。
  • 建议检查write和read的返回值,确认实际操作的字节数是否符合预期,避免出现部分写入/读取或错误:
// 检查写入结果
ssize_t write_len = write(fds[1], &temptotal, sizeof(int));
if (write_len == -1) {
    perror("write failed");
} else if (write_len != sizeof(int)) {
    fprintf(stderr, "Only wrote %zd bytes instead of %zu\n", write_len, sizeof(int));
}

// 检查读取结果
ssize_t read_len = read(fds[0], &temptotal, sizeof(int));
if (read_len == -1) {
    perror("read failed");
} else if (read_len != sizeof(int)) {
    fprintf(stderr, "Only read %zd bytes instead of %zu\n", read_len, sizeof(int));
}

内容的提问来源于stack exchange,提问作者Tearque Syrene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:20:00