65,187
社区成员




int execmd(char* cmd,char* result) {
char buffer[128]; //定义缓冲区
FILE* pipe = _popen(cmd, "r"); //打开管道,并执行命令
if (!pipe)
return 0; //返回0表示运行失败
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe)){ //将管道输出到result中
strcat(result,buffer);
}
}
_pclose(pipe); //关闭管道
return 1; //返回1表示运行成功
}
int CIPCexportDlg::execmd(char *cmd, char *result)
{
SECURITY_ATTRIBUTES sa;
HANDLE hWrite,hRead;
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD dwReadBytes;
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
if(!CreatePipe(&hRead,&hWrite,&sa,0))
{
MessageBox("Create Pipe Error!");
return 0;
}
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
char totalcmd[1024]="C:\\WINDOWS\\system32\\cmd.exe /c ";
strcat(totalcmd,cmd);
if(!CreateProcess(NULL,totalcmd,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
{
MessageBox("Create Process Error!");
return 0;
}
CloseHandle(hWrite);
ReadFile(hRead,result,4096,&dwReadBytes,NULL);
return 1;
}
// crt_popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char psBuffer[128];
FILE *pPipe;
/* Run DIR so that it writes its output to a pipe. Open this
* pipe with read text attribute so that we can read it
* like a text file.
*/
if( (pPipe = _popen( "dir *.c /on /p", "rt" )) == NULL )
exit( 1 );
/* Read pipe until end of file, or an error occurs. */
while(fgets(psBuffer, 128, pPipe))
{
printf(psBuffer);
}
/* Close pipe and print return value of pPipe. */
if (feof( pPipe))
{
printf( "\nProcess returned %d\n", _pclose( pPipe ) );
}
else
{
printf( "Error: Failed to read the pipe to the end.\n");
}
}