1

请问如何恢复原始写入的缓冲区?

size_t write(int fd, const void *buf, size_t count)
{
    static size_t (*write_func)(int, const void *, size_t) = NULL;

    /* get reference to original (libc provided) write */
    if (!write_func)
    {
        write_func = (size_t(*)(int, const void *, size_t))
                     dlsym(RTLD_NEXT, "write");
    }
    return  write_func(fd, buffer, sizeof (buffer));
}
4

2 回答 2

1

执行扩充的最有效方法之一是在原始缓冲区中切出要更改的字节,并拼接到增量中。这些被粘贴在一起,您可以writev用来写出所有内容。

struct iovec v[3];
v[0].iov_base = buf;
v[0].iov_len = position_of_new_data;
v[1].iov_base = new_data;
v[1].iov_len = new_data_len;
v[2].iov_base = (const char *)buf + beginning_of_the_end;
v[2].iov_len = count - beginning_of_the_end;
return writev(fd, v, 3);

这应该适用于阻塞 I/O。对于非阻塞 I/O,您将​​需要做更多的工作来隐藏write调用被拦截的事实。或者,您可以将描述符翻转为阻塞,然后在返回之前翻转回非阻塞。

于 2012-06-26T01:30:57.513 回答
0

像这样:

ssize_t write(int fd, const void *buf, size_t count)
{
    static size_t (*write_func)(int, const void *, size_t) = NULL;
    if (!write_func)
        write_func = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");

    // buf is const so, in order to change it, we need to make a copy:
    char tmp[count+1];  // <- it might be safer to use malloc here
    memcpy(tmp,buf,count);

    // modify tmp here
    tmp[count]='a';

    return  write_func(fd, tmp, count+1);
}

请让我知道,如果那是你想做的。

于 2012-06-25T21:57:25.360 回答