问题:关于句柄在进程间的继承

boodweb 2001-06-12 03:22:00
CreateProcess有个STARTUPINFO结构的参数
可以用STARTUPINFO结构中的hStdInput等传输任意的句柄吗
我看到Ben Ezzell的《Windows 2000环境下Visual C++编程从入门到精通》一书中用此方法传输管道句柄,于是我试着传输Mutex句柄,在win2000下另一进程中获得了相同的值,可是98下我把结构中三个句柄都赋了值,还是得不到正确句柄,请问这是为什么?
源程序:
// process1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "conio.h"

int main(int argc, char* argv[])
{
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle=TRUE;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor=NULL;
HANDLE hMutex=CreateMutex(&sa,FALSE,"123");
if(!hMutex) printf("Create Mutex Failed!\n");
STARTUPINFO si;
PROCESS_INFORMATION pi;
char string[20];
BOOL bSuc;

memset(&si,0,sizeof(STARTUPINFO));
si.cb=sizeof(STARTUPINFO);
si.dwFlags=STARTF_USESTDHANDLES;
si.hStdOutput=hMutex;
si.hStdError=hMutex;
si.hStdInput=hMutex;
printf("Process1:hMutex=0x%x\n",hMutex);

CreateProcess("process2\\debug\\process2.exe",NULL,NULL,NULL,
TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi);

printf("Sleeping...\n");
Sleep(2000);
printf("Begin to wait...\n");
if(WAIT_TIMEOUT!=WaitForSingleObject(hMutex,INFINITE))
printf("Get it!\n");

ReleaseMutex(hMutex);
bSuc=CloseHandle(hMutex);
if(!bSuc) printf("Process1:Close hMutex Error!\n");
printf("Now,press any key to see if the mutex is still active\n");
getch();

hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"123");
if(!hMutex)
printf("Process1:No 123 Exists!\n");
else{
printf("Process1:Still 123 Exists!\n");
CloseHandle(hMutex);
}
return 0;
}

// process2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "conio.h"

int main(int argc, char* argv[])
{
HANDLE hMutex;
BOOL bSuc;
char string[20];

hMutex=GetStdHandle(STD_INPUT_HANDLE);
printf("Process2:hMutex=0x%x",hMutex);
hMutex=GetStdHandle(STD_OUTPUT_HANDLE);
printf("Process2:hMutex=0x%x",hMutex);
hMutex=GetStdHandle(STD_ERROR_HANDLE);
printf("Process2:hMutex=0x%x",hMutex);
//printf("process2:hMutex=0x%x\n",hMutex);
if(WAIT_TIMEOUT==WaitForSingleObject(hMutex,100)){
printf("Time Out!\n");
getch();
CloseHandle(hMutex);
exit(0);
}
printf("Press any key to release hMutex\n");
getch();
ReleaseMutex(hMutex);
printf("Press any key to close hMutex\n");
getch();
bSuc=CloseHandle(hMutex);
if(!bSuc) printf("Process2:Close hMutex Error!\n");

return 0;
}
...全文
93 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
boodweb 2001-06-14
  • 打赏
  • 举报
回复
有人知道吗?
boodweb 2001-06-12
  • 打赏
  • 举报
回复
To SuperProgMan(编程者):
在2000下是成功的
SuperProgMan 2001-06-12
  • 打赏
  • 举报
回复
用OpenMutex或DuplicateHandle一个
huangbeyond 2001-06-12
  • 打赏
  • 举报
回复
关注,马上去测试!

15,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧