我想要具有 FIFO 的服务器-客户端模型和客户端获取目录路径,但我收到错误“读:错误地址”和“写:错误地址”。
客户端
服务器错误:“读取:地址错误”
客户端错误:“写入:地址错误”
最佳答案
您可能误用了 read
和 write
的返回值。成功后,它们返回正值,您将它们作为错误处理。
此外,读取字符串的大小时也是未知的。所以 strlen
是不合适的。
if( (controlRead = read(fdp,pathName,sizeof(pathName)) ) <= 0)
{
// error ...
与write
条件相同。
传输字符串时,最好也传输字符串长度:
写作:
void write_string(int fd, const char *string)
{
size_t len = strlen(string);
write(fd, &len, sizeof(len));
write(fd, string, len);
}
阅读:
void read_string(int fd, char *buffer, size_t size, size_t *len)
{
size_t t_len;
read(fd, &t_len, sizeof(t_len));
if (t_len > size) t_len = size;
read(fd, buffer, t_len);
if (t_len < size) buffer[t_len] = 0; // null-terminate if there is enough space
if (len) *len = t_len; // return length if wanted
}
关于C: "read: Bad Address"和 "write: Bad Address",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131468/