简体   繁体   English

如何通过命令提示符启动exe并从命令提示符窗口获取文本

[英]How to launch an exe by command prompt and get text from command prompt window

jarsigner.exe takes a parameter and prints some text to console: jarsigner.exe带有一个参数,并向控制台输出一些文本:

string command = "jarsigner.exe -verify test.jar";
system(command.c_str());

when I run this code, command prompt window appears and it prints jar is verified or jar is unsigned to console. 当我运行此代码时,将出现命令提示符窗口,并显示jar is verifiedjar is unsigned到控制台。

How can I get this result string from the console? 如何从控制台获取此结果字符串?

您可以尝试ReadConsoleOutputCharacter

I used Google to find this . 我用Google找到了这个

EDIT: Does jarsigner not return error codes? 编辑: jarsigner不返回错误代码吗? Like 0 on success and 1 on failure? 喜欢成功的0和失败的1 You could use CreateProcess and trap the return code. 您可以使用CreateProcess并捕获返回代码。

You could redirect stdout to to a file (jarsigner.exe > outfile.txt) and then parse the contents of the file using a utility like a perl or shell script. 您可以将stdout重定向到文件(jarsigner.exe> outfile.txt),然后使用诸如perl或shell脚本之类的实用程序解析文件的内容。

Alternatively, you can redirect stdout in your application using the dup, _open_osfhandle , or freopen functions. 另外,您可以使用dup, _open_osfhandlefreopen函数在应用程序中重定向标准输出。

i created new process and redirect its stdout to text file, it works. 我创建了新进程,并将其标准输出重定向到文本文件,它可以工作。

STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;

HANDLE hOutFile;

ZeroMemory( &si, sizeof(si) );
ZeroMemory( &pi, sizeof(pi) );
ZeroMemory( &sa, sizeof(sa) );

si.cb = sizeof(si);
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES ;

sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = true;

// Create output file and get file handle
hOutFile  = CreateFile ( TEXT(outFilePath.c_str()),
        FILE_SHARE_WRITE,
        0,
        &sa, // provide SECURITY_ATTRIBUTES
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

// Assign StartInfo StdOutput to file handle
si.hStdOutput = hOutFile ;

LPTSTR szCmdline = TEXT( command.c_str() );
 if( !CreateProcess( NULL,   // No module name (use command line)
    szCmdline,        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    true,          // Set handle inheritance to TRUE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    TEXT(jarSignerExeDir.c_str()), // Use jarSignerExeDir FOR starting directory
    &si,            // Pointer to STARTUPINFO structure
    &pi )           // Pointer to PROCESS_INFORMATION structure
)
{
   ShowMessage( "CreateProcess failed (%d).\n" + GetLastError() );
}

// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );

// Close process,thread and file handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
CloseHandle(hOutFile);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM