How to parse tshark arguments in ShellExecute function - c++

I want to call tshark.exe from a c++ script via ShellExecute. Is there any way to parse cmd arguments to the application?
e.g. specify output file like this
tshark -w output.pcap
Here is the code
#include <Windows.h>
#include <shellapi.h>
int main()
{
ShellExecute(NULL, "open", "tshark.exe", NULL, "C:\Program Files\Wireshark", SW_SHOWDEFAULT);
return 0;
}

The 4th parameter to ShellExecute() passes command-line arguments to the new process, eg:
ShellExecute(NULL, "open", "tshark.exe", "-w output.pcap", "C:\\Program Files\\Wireshark", SW_SHOWDEFAULT);
Though, you really should be using CreatProcess() instead (ShellExecute() is just going to call it anyway):
STARTUPINFO si = {};
PROCESS_INFORMATION pi = {};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWDEFAULT;
char cmd[] = "tshark.exe -w output.pcap";
if (CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, "C:\\Program Files\\Wireshark", &si, &pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}

Related

CreateProcess returns true but does not execute with regedit

I am trying to dump a portion of the windows registry in a .txt file using the CreateProcess function. The code is along the lines of
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
CString cmdLine = "\"C:\\WINDOWS\\regedit.exe\" /e \"c:\\dump\\TestReg.txt\"
\"HKEY_LOCAL_MACHINE\\SOFTWARE\\MYSOFT\\\"";
LPSTR pCmdLine = (LPSTR)(const char*)cmdLine;
BOOL oc = CreateProcess(NULL, pCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if(oc == TRUE)
{
WaitForSingleObject(pi.hProcess, 1000);
GetExitCodeProcess(pi.hProcess, &exitCode);
if(exitCode != 0) ret = -1;
}
What I know
The CreateProcess returns TRUE and the last blocks executes
The process waits for the end and exits normally
However no file is produced at the end
The command line string works fine in command line, even when it operates from the same directory where the program is operating.
I have found something that is potentially useful where someone had basically the same problem. In the end it resulted in a dependency clash but the link does not explain very well how it was detected or fixed.

Is it possible to prevent system() from stealing focus? [duplicate]

I am coding a C program in Dev-C++, and I need to use a couple of Windows (CMD) commands. It is easy, but when the command in the system() function is executed, the program runs the console in the execution.
An example:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
system("if not exist c:\my_docs\doc.txt (xcopy /Y doc.txt c:\my_docs\)"); // Cmd command
system("pause");
return 0;
}
Exists other function, or a modification that do not shows the console?
Thanks you! Best regards.
You can use WinExec("your cmd command", SW_HIDE); instead of system("cmd command").
You can do it with CreateProcess.
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (CreateProcessW(command, arg, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
As FigBug stated, CreateProcess() is the way to go, but I don't think that CreateProcess() can execute a shell if statement. You may need to pass it something like this as a command:
"cmd.exe /c \"if not exist c:\my_docs\doc.txt (xcopy /Y doc.txt c:\my_docs\)\""
But a better solution might be to use CreateFile() to test if a file exists and CopyFile() to copy it.
NOTE: My answer is not necessarily tailored to your specific question, but this Q&A is the top Google result for "Windows system without command prompt" and other similar queries.
Here's a way to execute commands without a new cmd.exe window. Based on Roland Rabien's answer and MSDN, I've written a working function.
#include "AtlBase.h"
#include "AtlConv.h"
int windows_system(const char *cmd) {
PROCESS_INFORMATION p_info;
STARTUPINFO s_info;
DWORD ReturnValue;
CA2T programpath(cmd);
memset(&s_info, 0, sizeof(s_info));
memset(&p_info, 0, sizeof(p_info));
s_info.cb = sizeof(s_info);
if (CreateProcess(programpath, NULL, NULL, NULL, 0, 0, NULL, NULL, &s_info, &p_info)) {
WaitForSingleObject(p_info.hProcess, INFINITE);
GetExitCodeProcess(p_info.hProcess, &ReturnValue);
CloseHandle(p_info.hProcess);
CloseHandle(p_info.hThread);
}
return ReturnValue;
}
Works on all Windows platforms. Call just like you would system().
int win_system(const char *command)
{
// Windows has a system() function which works, but it opens a command prompt window.
char *tmp_command, *cmd_exe_path;
int ret_val;
size_t len;
PROCESS_INFORMATION process_info = {0};
STARTUPINFOA startup_info = {0};
len = strlen(command);
tmp_command = malloc(len + 4);
tmp_command[0] = 0x2F; // '/'
tmp_command[1] = 0x63; // 'c'
tmp_command[2] = 0x20; // <space>;
memcpy(tmp_command + 3, command, len + 1);
startup_info.cb = sizeof(STARTUPINFOA);
cmd_exe_path = getenv("COMSPEC");
_flushall(); // required for Windows system() calls, probably a good idea here too
if (CreateProcessA(cmd_exe_path, tmp_command, NULL, NULL, 0, CREATE_NO_WINDOW, NULL, NULL, &startup_info, &process_info)) {
WaitForSingleObject(process_info.hProcess, INFINITE);
GetExitCodeProcess(process_info.hProcess, &ret_val);
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
}
free((void *) tmp_command);
return(ret_val);
}

MFC Command Window Command

In MFC I want to Create a process by opening Command Window and executing a command in that say open notepad.
i Found this tried it didn't work
STARTUPINFO sInfo = {0};
sInfo.cb = sizeof(sInfo);
PROCESS_INFORMATION pInfo = {0};
CreateProcess("C:\\WINDOWS\\System32\\cmd.exe",""0,0,TRUE,
NORMAL_PRIORITY_CLASS,0,0,&sInfo,&pInfo);
You're not telling cmd to do anything. Try this:
CreateProcess(0, "C:\\WINDOWS\\System32\\cmd.exe /c notepad.exe", 0, 0, TRUE, 0, 0, 0, &sInfo, &pInfo);
But maybe this is easier
ShellExecute(0, "open", "cmd.exe", "/C notepad.exe", 0, SW_HIDE);
Or even this:
system("notepad.exe");
Go to the MSDN document we can see, you don't specify the second parameter that is the command line to excute.
On the other hand, there are no NORMAL_PRIORITY_CLASS enum item for the sixth parameter. You should do like this:
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = TRUE;
TCHAR cmdline[] =TEXT(" notepad.exe");
BOOL bRet = ::CreateProcess (
TEXT("C:\\WINDOWS\\System32\\cmd.exe"),
cmdline,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi);

C++ CreateProcess - System Error #2 can't find file - what is wrong with my file path?

I am trying to open a PDF via Firefox with CreateProcess(), I am a beginner and know nothing about using CreateProcess, but in my last question someone pointed out the MSDN on it... it shows that:
To run a batch file, you must start the command interpreter;
set lpApplicationName to cmd.exe and set lpCommandLine to the
following arguments: /c plus the name of the batch file.
Therefore I created a batch file that runs perfectly fine with the system() command, there are no problems with the batch file.
I can't figure out why the system can't find the file and I don't know if its the batch file, the exe in the batch file, the PDF doc in the batch file or the location of cmd.exe... Any help is greatly appreciated...
void openPDF(char scansQueue[][MAX_NAME], int index)
{
// build batch file
char openPath[300];
char procCommand[MAX_NAME]="C:\\firefox";
char cmdEXE[MAX_NAME]="C:\\Windows\\System32\\cmd.exe";
fstream outfile;
outfile.open("C:\\firefox.bat");
copyCString(openPath,"\"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe\"");
outfile << openPath;
outfile << ' ';
copyCString(openPath,"\"C:\\Scans\\");
catArray(openPath,scansQueue[index]);
catArray(openPath,"\"");
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
cout<<"PROCESS ATTEMPT"<<endl;
if(!CreateProcess((LPCTSTR)cmdEXE ,(LPWSTR)procCommand, NULL, NULL, false, 0, NULL, NULL, &si, &pi))cout << GetLastError();cout<<"PROCESS FAILED TO EXECUTE!!!";
}
This assumes the whole batch file thing is part of an XY problem, in that you don't really need to make a batch file, you really just want to launch Firefox with a command line parameter.
I also assume you don't really need to pass the whole array of filenames with an index for which to use, instead you should just pass the filename by itself as I did where I called the function.
#include <Windows.h>
#include <stdio.h>
void MsgBoxLastError()
{
LPWSTR lpMsgBuf = NULL;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpMsgBuf,
0, NULL ) != 0)
{
MessageBox(NULL, lpMsgBuf, L"Error", MB_OK);
}
LocalFree(lpMsgBuf);
}
void OpenWithFirefox(const char* Filename)
{
const WCHAR pathToFirefox[] = L"C:/Program Files (x86)/Mozilla Firefox/firefox.exe";
const WCHAR scanPrefix[] = L"file://C:/Scans/";
WCHAR fullCommandLine[MAX_PATH] = {0};
//Build full command line
swprintf_s(fullCommandLine, L"\"%s\" \"%s%S\"", pathToFirefox, scanPrefix, Filename);
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
BOOL success = CreateProcess(NULL, fullCommandLine, NULL, NULL, false, 0, NULL, NULL, &si, &pi);
if(success)
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
MsgBoxLastError();
}
}
int main()
{
const int MAX_NAME = 13;
char scansQueue[][MAX_NAME] =
{
"file1.pdf",
"file2.pdf"
};
for(int i = 0; i < 2; ++i)
{
OpenWithFirefox(scansQueue[i]);
}
return 0;
}

How to redirect in, out and err streams from process created with CreateProcess function? [duplicate]

I tried using CreateProcess to run a simple command like hg > test.txt. I tried running the string as a whole (as opposed to separating it into an application name and its parameters). Why does CreateProcess(0, "notepad.exe test.txt", ...) work but CreateProcess(0, "hg > test.txt", ...) does not?
The code below creates a console-less process with stdout and stderr redirected to the specified file.
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
HANDLE h = CreateFile(_T("out.log"),
FILE_APPEND_DATA,
FILE_SHARE_WRITE | FILE_SHARE_READ,
&sa,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL );
PROCESS_INFORMATION pi;
STARTUPINFO si;
BOOL ret = FALSE;
DWORD flags = CREATE_NO_WINDOW;
ZeroMemory( &pi, sizeof(PROCESS_INFORMATION) );
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof(STARTUPINFO);
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = NULL;
si.hStdError = h;
si.hStdOutput = h;
TCHAR cmd[]= TEXT("Test.exe 30");
ret = CreateProcess(NULL, cmd, NULL, NULL, TRUE, flags, NULL, NULL, &si, &pi);
if ( ret )
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
return -1;
}
You can't use stdout redirection in the command line passed to CreateProcess. To redirect stdout you need to specify a file handle for the output in the STARTUPINFO structure.
You are also making another, more subtle, mistake. The second parameter, lpCommandLine must point to writeable memory because CreateProcess overwrites the buffer. If you happen to be using the ANSI version of the function then you will get away with this, but not for the Unicode version.
The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.
Microsoft has an example how to redirect the standard output:
http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx.
CreateProcess() launches processes, it is not a command line itnerpreter. It doesn't know what ">" is and won't do the stream redirection for you. You need to open the file test.txt yourself and pass the handle to it to CreateProcess inside the STARTUPINFO structure:
CreateProcess
STARTUPINFO
you should run process cmd.exe with params "/c command line".
This will redirect the output to a file or to organize a pipeline through CreateProcess.