Linux中的函数插入(写入函数)

时间:2012-06-25 21:23:36

标签: c linux

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

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));
}

2 个答案:

答案 0 :(得分: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调用被截获的事实。或者,您可以将描述符翻转为阻塞,然后在返回之前翻转回非阻塞状态。

答案 1 :(得分: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);
}

请告诉我,如果那是你想做的事。