复制句柄,然后关闭原来的句柄

Duplicating a handle and closing the original one afterwards

本文关键字:句柄 原来 然后 复制      更新时间:2023-10-16

我正在开发以下类:

class Handle
{
public:
    inline Handle()
    {
        handle = INVALID_HANDLE_VALUE;
    }
    inline Handle(HANDLE handle)
    {
        this->handle = copyHandle(handle);
    }
    inline Handle(const Handle& rhs)
    {
        this->handle = copyHandle(rhs.handle);
    }
    inline bool isValid()
    {
        return handle != INVALID_HANDLE_VALUE;
    }
    inline HANDLE getNativeHandle()
    {
        return copyHandle(this->handle);
    }
    inline void close()
    {
        if(handle != INVALID_HANDLE_VALUE)
        {
            CloseHandle(handle);
            handle = INVALID_HANDLE_VALUE;
        }
    }
    inline virtual ~Handle()
    {
        if(handle != INVALID_HANDLE_VALUE)
            CloseHandle(handle);
    }
protected:
    HANDLE handle;
    HANDLE copyHandle(HANDLE copyable);
};

cpp文件:

HANDLE Handle::copyHandle(HANDLE copyable)
{
    HANDLE ret;
    HANDLE current = GetCurrentProcess();
    if(copyable == INVALID_HANDLE_VALUE)
        ret = copyable;
    else if(DuplicateHandle(current, copyable, current, &ret, 0, TRUE , DUPLICATE_SAME_ACCESS) == 0)
        {
            if(GetLastError() == ERROR_ACCESS_DENIED)
                throw SecurityException("The handle duplication was denied!");
            else
                throw InvalidHandleException("The handle could not be duplicated!");
        }
    return ret;
}

类似乎正常工作,但复制句柄,然后关闭原始句柄,然后复制新句柄将抛出异常或Windows Errorcode 6,这是"无效句柄值"。

目前,我认为关闭原始手柄也会导致副本的完全销毁,使我以后无法使用它们。

Handle test = CreateMutex(NULL, FALSE, NULL);
Handle copy = test;
test.close();
std::cout << copy.getNativeHandle() << std::endl; // throws an exception, but uses the same function as above
return 0;

是否有可能复制句柄,这样它就不依赖于原始句柄的存在?

试试这个实现:

class Handle
{
public:
    Handle(HANDLE ahandle = INVALID_HANDLE_VALUE)
    {
        handle = ahandle; // <- take ownership of the original, not a copy
    }
    Handle(const Handle& src)     
    {
        handle = src.duplicate(); // <-- take ownership of a copy
    }
    ~Handle()
    {
        close();
    }
    void close()
    {
        if (handle != INVALID_HANDLE_VALUE)
        {
            CloseHandle(handle);
            handle = INVALID_HANDLE_VALUE;
        }
    }
    HANDLE getNativeHandle() const
    {
        return handle;
    }
    bool isValid() const
    {
        return (handle != INVALID_HANDLE_VALUE);
    }
    HANDLE duplicate()
    {
        if (handle == INVALID_HANDLE_VALUE)
            return handle;
        HANDLE ret, current = GetCurrentProcess();
        if (!DuplicateHandle(current, handle, current, &ret, 0, TRUE, DUPLICATE_SAME_ACCESS))
        {
            if (GetLastError() == ERROR_ACCESS_DENIED)
                throw SecurityException("The handle duplication was denied!");
            else
                throw InvalidHandleException("The handle could not be duplicated!");
        }
        return ret;
    }
    Handle& operator=(HANDLE &rhs)
    {
        close();
        handle = rhs; // <-- take ownership of the original, not a copy
        return *this;
    }
    Handle& operator=(const Handle &rhs)
    {
        close();
        handle = rhs.duplicate(); // <-- take ownership of a copy
        return *this;
    }
protected:
    HANDLE handle;
};

附带说明,一些API函数使用NULL而不是INVALID_HANDLE_VALUE,而有些不使用CloseHandle()。你应该考虑考虑这些差异。我建议更新Handle类以使用c++模板,这样您就可以在每个实例的基础上专门化行为,例如:

struct InvalidHandleTrait
{
    static const HANDLE InvalidValue = INVALID_HANDLE_VALUE;
};
struct NullHandleTrait
{
    static const HANDLE InvalidValue = NULL;
};
struct CloseHandleTrait
{
    static bool close(HANDLE handle)
    {
        return CloseHandle(handle);
    }
};
template< typename HandleTrait = InvalidHandleTrait, typename CloseTrait = CloseHandleTrait >
class Handle
{
public:
    Handle(HANDLE ahandle = HandleTrait::InvalidValue)
    {
        handle = ahandle; // <- take ownership of the original, not a copy
    }
    Handle(const Handle& src)     
    {
        handle = src.duplicate(); // <-- take ownership of a copy
    }
    ~Handle()
    {
        close();
    }
    void close()
    {
        if (handle != HandleTrait::InvalidValue)
        {
            CloseTrait::close(handle);
            handle = HandleTrait::InvalidValue;
        }
    }
    HANDLE getNativeHandle() const
    {
        return handle;
    }
    bool isValid() const
    {
        return (handle != HandleTrait::InvalidValue);
    }
    HANDLE duplicate()
    {
        if (handle == HandleTrait::InvalidValue)
            return handle;
        HANDLE ret, current = GetCurrentProcess();
        if (!DuplicateHandle(current, handle, current, &ret, 0, TRUE, DUPLICATE_SAME_ACCESS))
        {
            if (GetLastError() == ERROR_ACCESS_DENIED)
                throw SecurityException("The handle duplication was denied!");
            else
                throw InvalidHandleException("The handle could not be duplicated!");
        }
        return ret;
    }
    Handle& operator=(HANDLE &rhs)
    {
        close();
        handle = rhs; // <-- take ownership of the original, not a copy
        return *this;
    }
    Handle& operator=(const Handle &rhs)
    {
        close();
        handle = rhs.duplicate(); // <-- take ownership of a copy
        return *this;
    }
protected:
    HANDLE handle;
};

您还需要为Handle定义一个赋值操作符。我怀疑真正崩溃的代码是这样的:

Handle test = CreateMutex(NULL, FALSE, NULL);
Handle copy;
copy= test; // assigned instead of using copy constructor
test.close();
std::cout << copy.getNativeHandle() << std::endl;
return 0;

如果没有赋值操作符,就不能正确地复制句柄。