我正在尝试使用
CreateProcess
运行命令并将 STDOUT
重定向到在客户端连接到的同一台机器(服务器)上创建的命名管道,并将接收输出数据。
在服务器上创建命名管道:
char pipeunc[MAX_PATH];
SECURITY_DESCRIPTOR sd;
SECURITY_ATTRIBUTES sa;
// Setup DACL for NamedPipe
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);
SetSecurityDescriptorControl(&sd, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
sa = { sizeof(sa), &sd, FALSE };
sprintf(pipeunc, "\\\\.\\pipe\\%s", pipename);
// Create the named-pipe
HANDLE pipe = CreateNamedPipeA(
pipeunc,
PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE,
PIPE_UNLIMITED_INSTANCES,
0,
0,
0,
&sa
);
if (pipe == NULL) {
fprintf(fd, "Error: CreateNamedPipeA: %d\n", GetLastError());
return NULL;
}
CreateProcess
在服务器上:
HANDLE pipeh;
STARTUPINFOA sinfo;
PROCESS_INFORMATION pinfo;
bool res;
pipeh = remote::SetupNamedPipe(pipe_name, fd);
memset(&sinfo, 0, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
sinfo.dwFlags |= STARTF_USESTDHANDLES;
sinfo.hStdOutput = sinfo.hStdError = pipeh; // Redirect output to named-pipe
// Wait until client connects.
ConnectNamedPipe(pipeh, NULL);
SetHandleInformation(pipeh, HANDLE_FLAG_INHERIT, 0);
res = CreateProcessA(
NULL,
const_cast<LPSTR>(cmd),
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&sinfo,
&pinfo
);
连接到命名管道(客户端):
static HANDLE pipeh;
// Create a handle to the remote pipe
pipeh = CreateFileA(
const_cast<LPCSTR>(PipeName),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL
);
ReadFile
,客户端
while(1){
res = ReadFile(
pipeh_read, // is the same handle(pipeh)
buf,
PIPE_MAX_READ_SIZE,
NULL,
NULL
);
printf("%s\n", buf);
if (!res) {
puts("Process returned.");
#ifdef DEBUG
printf("ReadFile code: %d\n", GetLastError());
#endif
return;
}
}
您的管道服务器安全属性不能被继承。见继承。并且您禁用了要继承的服务器管道。根据SetHandleInformation,
要设置或清除 dwFlags 中的相关位标志,您必须设置一个 在 dwMask 中更改掩码位标志。
要启用继承,请使用
BOOL res = SetHandleInformation(hPipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);