在不同的过程中,使用DuplicateHandle(...)函数如何共享一个句柄? [英] In the process of different, use DuplicateHandle(...) function how to share a handle?

查看:111
本文介绍了在不同的过程中,使用DuplicateHandle(...)函数如何共享一个句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

g_hComm = CreateFile ("COM1",GENERIC_READ | GENERIC_WRITE, 0, 0, NULL, OPEN_EXISTING, NULL);



如何将g_hComm 此句柄与其他使用的进程共享?

我是新手,请尝试举例.谢谢!



How to put the g_hComm this handle Shared with other process used?

I am a novice, try to give examples. thank you!

推荐答案

首先,如果您是新手,我建议您避免在进程之间共享文件以及避免重复使用任何句柄:1)这些相关技术不是很容易理解; 2)它们不安全; 3)这不是推荐的做法;建议的做法应保持流程的主要特征-它们之间的强隔离,而打破这种隔离是一个有问题的做法.如果有的话,它可能会用在一些真正罕见且复杂的技术中.

现在,我看不到所获得的手柄重复的用途是什么,因为-您将如何使用它?问题是您调用CreateFiledwShareMode == 0的第三个参数.如果您不共享文件,如何使用该句柄的副本?您需要使用FILE_SHARE_READFILE_SHARE_WRITEFILE_SHARE_READ | FILE_SHARE_WRITE.阅读,所有内容均已说明:
http://msdn.microsoft.com/zh-我们/library/windows/desktop/aa363858%28v=vs.85%29.aspx [ http://msdn.microsoft.com/zh-我们/library/windows/desktop/ms724251%28v=vs.85%29.aspx [
First of all, if you are a novice, I would recommend you to avoid sharing files between processes and duplication of any handles: 1) these related techniques are not very easy for understanding; 2) they are unsafe; 3) this is not a recommended practice; a recommended practices should maintain main feature of the processes — strong isolation between them, and breaking through this isolation is a questionable practice. It can be used probably in some really rare and sophisticated technology, if any.

Now, I don''t see what could be the use of duplication of the handle you have obtained, because — how would you use it? The problem is the third parameter of your call to CreateFile, dwShareMode == 0. How can you use the handle''s duplicate if you are not sharing the file? You need to use FILE_SHARE_READ, or FILE_SHARE_WRITE or, say, FILE_SHARE_READ | FILE_SHARE_WRITE. Read, everything is explained:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx[^].

And them you can share the handler, either in this or a foreign process. You need to pass the original handle and a handle to a different process or obtain a handle of a foreign process, use it to duplicate a handle and pass a handle duplicate back to a foreign process. Everything is explained:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724251%28v=vs.85%29.aspx[^].

Now, how to communicate between processes is your problem, a separate one. This is called Inter-Process Communication (IPC). You just need to learn about it; this is a separate big topic. You can use sockets, named pipes, shared memory and so on.

Before going into all of that, please re-read my first paragraph above and think is you really need it. Also, when asking questions, it''s the best to start with explaining your purpose and your ultimate goals.

—SA


这篇关于在不同的过程中,使用DuplicateHandle(...)函数如何共享一个句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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