Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For example:
C++
g_hComm = CreateFile ("COM1",GENERIC_READ | GENERIC_WRITE, 0, 0, NULL, OPEN_EXISTING, NULL);


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

I am a novice, try to give examples. thank you!
Posted
Updated 19-May-12 20:48pm
v2
Comments
Sergey Alexandrovich Kryukov 19-May-12 22:49pm    
First of all. it's good to understand why doing so...
--SA

1 solution

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
 
Share this answer
 
Comments
VJ Reddy 21-May-12 12:57pm    
Nice answer. 5!
Sergey Alexandrovich Kryukov 21-May-12 14:10pm    
Thank you, VJ.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900