“双重关闭"交易是否安全?使用CloseHandle的句柄? [英] Is it safe to "double-close" a handle using CloseHandle?

查看:70
本文介绍了“双重关闭"交易是否安全?使用CloseHandle的句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多次调用CloseHandle有什么意义?

What are the implications of calling CloseHandle more than once?

文档说您不应该",但我认为我有一个现实的案例,其中使用命名管道,其中的句柄可能在外部关闭(请参见文章结尾).

The docs say "you shouldn't" but I think I have a realistic case with named pipes where a handle might be closed externally (See end of post).

在这种情况下,CloseHandle在调试模式下会引发异常,这向我表明开发人员认为这很严重,但是文档并不清楚.

CloseHandle throws an exception in debug mode in this case, which suggests to me the developers think this is serious, but the docs aren't exactly clear.

(礼貌要求:请避免回答就是不要!" :-).当然,应该避免多次关闭手柄,当然,有很好的技术可以帮助您解决这一问题:如果您不这样做,我只是对发生的事情感兴趣.

(Polite request: Please avoid the answer "just don't!" :-). Of course one should avoid closing a handke more than once, and of course there are good techniques to help with this: I'm just interested in what happens if you don't).

我听说有人建议,如果操作系统迅速重用了该句柄,您可能最终会关闭另一个不同的句柄.

I've heard some people suggest that if the handle was quickly reused by the OS you might end up closing another, different handle.

这可能吗?

Windows如何选择句柄ID?

How does Windows choose handle IDs?

是否可以保证多久重复使用一个句柄值?

Is there any guarantee about how regularly a handle value will be reused?

(例如,TCP确保端口号不能在特定时间范围内重用).

(e.g. TCP ensures that a port number cannot be reused within a certain timeframe).

可以关闭所有手柄类型的手柄吗?例如,我是否可以认为我正在关闭管道但最终关闭了一个事件?

Can you close handles accross handle types? E.g., could I be thinking I'm closing a pipe but end up closing an Event?

谢谢!

约翰

(上下文:我正在客户机/服务器模型中使用命名管道.在我看来,要确保确切地保证一方能够关闭该句柄是非常困难的,例如在进程崩溃/死机的情况下.也许我是错的,但是我想当然可以认为MSDN示例代码允许客户端关闭共享句柄,然后当服务器尝试关闭共享句柄时,它已经关闭).

(Context to this: I'm using named pipes in a client/server model. It seems to me very difficult to ensure that exactly one party is guaranteed to close the handle, e.g. in process crash/killed case. Perhaps I'm wrong, but certainly the MSDN sample code seems to my mind to allow the client to close the shared handle, and then when the server tries to close it, it is already closed).

推荐答案

简单到可以检查:

HANDLE h = 0;
h = CreateMutex(NULL, TRUE, NULL);
printf("%X\n", h);
CloseHandle(h);
h = 0;
h = CreateMutex(NULL, TRUE, NULL);
printf("%X\n", h);

在我的WinXP x64中,这产生了:

In my WinXP x64 this produced:

2E8
2E8

所以你有它.
与TCP端口不同,句柄可立即回收.

So there you have it.
Unlike TCP ports, handles are recycled immediately.

使用您喜欢的API或其任意组合重复此实验.

Repeat this experiment with your favorite API or any mix thereof.

这篇关于“双重关闭"交易是否安全?使用CloseHandle的句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆