I am using CreateProcess, but I can't start a process I am using the following code but I am getting the error "Invalid access to memory location" but I don't know why.
Is there any problem with my code?
#include <Windows.h>
#include <stdio.h>
//#include "common.h"
int main(void)
{
DWORD creation_flags = DEBUG_PROCESS;
STARTUPINFO startupinfo;
PROCESS_INFORMATION process_information;
char *path_to_exe = "D:\\dbg\\calc.exe";
startupinfo.dwFlags = 0x1;
startupinfo.wShowWindow = 0x0;
startupinfo.cb = sizeof(startupinfo);
if(CreateProcess( path_to_exe,
NULL,
NULL,
NULL,
NULL,
creation_flags,
NULL,
NULL,
&startupinfo,
&process_information)){
printf("We have successfully launched the process!\n");
printf("[*] PID: %d\n", process_information.dwProcessId);
}
else
printf("[*] Error: %d.\n", GetLastError());
}
You have only filled in 3 fields of the startupinfo Structure.
The remaining fields are filled with garbage, and some of that garbage is likely leading to bad problems.
You should fully initialize the structure, explicitly putting NULL, 0 and other "empty" values where you don't want to specify anything.
Try zeroing the startup info structure. Some of it's members (e.g. lpTitle) are used even if you don't set an explicit flag.
Also beware that CreateProcess may temporarily write to the application name string, so you may want to avoid passing a read-only string literal. This only happens with the unicode version of the function though, at least on recent versions of Windows.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 months ago.
Improve this question
i have to pass a string into my process, but for some reason i can't
i've tried to pass a path and an argument in function, i've tried to put a \0 after the argument, i've tried to pass an argument or space + an argument but it doesn't passes.
could you please help me?
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
using namespace std;
void _tmain(int argc, TCHAR* argv[])
{
cout << "we are here!\n";
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
string first = "C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe"; //Initializing a name of our file
wstring temp = wstring(first.begin(), first.end()); // Initializing an object of wstring
LPCWSTR file_name = temp.c_str(); // Applying c_str() method on temp
string s1 = " 1.exe 1\0";
LPWSTR cl1 = (LPWSTR)s1.c_str();
// Start the child process.
if (!CreateProcess(file_name, // No module name (use command line)
cl1, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Creating console for our application
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
cout << "we are done!\n";
}
thanks for your help in advance
Are you compiling in Unicode or Multibyte (MBCS)?
Assuming you are compiling in Unicode you can avoid the use of string objects and use wstring objects instead.
To initialize a wstring you have to prefix the double quoted string with an L, i.e.
wstring first(L"C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe");
So, you can avoid the use of temp variable.
Note: Is more efficient to initialize a (w)string using the constructor instead of the assignment operator.
Also, the cast in
string s1 = " 1.exe 1\0";
LPWSTR cl1 = (LPWSTR)s1.c_str();
is nos valid, as s1.c_str() return type is const char* (or LPCSTR).
Instead, you can declare
wstring s1(L" 1.exe 1\0");
LPCWSTR cl1 = s1.c_str();
In fact, you don't need to assign the result of c_str() to another variable. You can call to c_str() when you are calling to CreateProcess. The code could be something as:
//Initializing a name of our file
wstring first(L"C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe");
wstring s1(L" 1.exe 1\0");
// Start the child process.
if (!CreateProcess(first.c_str(), // No module name (use command line)
const_cast<LPWSTR>(s1.c_str()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Creating console for our application
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
If you are compiling with MBCS you should change wstring by string and remove the L prefix when initializing strings. The rest of the code could remain the same.
The saga continues...
I've searched the web, i've searched on StackOverflow, i found many hope giving answers/solutions, but somehow they have all failed (up)on me (including the ones related to ShellExecute(Ex) ).
How to hide a (flashing) CMD window (incl. arguments) using CreateProcess??
I basically want to call/execute a set of conditional/native cmd.exe commands (i.e. FOR /F, and ||), but also an external command FIND(STR).exe. And this, without showing a (flashing) CMD window.
But even hiding something as simple as "cmd.exe /C ECHO ...flashing window is bad..." seems impossible to do.
The code i've tried (including many variations related to the dwFlags and wShowWindow flags
#include <windows.h>
int main()
{
char cmdline[] = "cmd.exe /c ECHO ...flashing window is bad...";
PROCESS_INFORMATION pi;
STARTUPINFO si;
// memset(&si,0,sizeof(STARTUPINFO));
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
// si.dwFlags = STARTF_USESTDHANDLES;
// si.dwFlags = CREATE_NO_WINDOW;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
// si.wShowWindow = CREATE_NO_WINDOW;
CreateProcess(NULL, (LPSTR) cmdline, NULL, NULL, 0, 0, NULL, NULL, &si, &pi);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
// ExitProcess;
return 0;
}
I don't want to rely on external programs i.e. .vbs (Windows Scripting Host) or shortcut tricks, but simply a standalone compiled .exe.
Is this (really) too much to ask, or am i doing it (completely) wrong?
Thanks...
Update: You also seem to confuse CreateProcess flags (its dwCreationFlags argument) with the member of STARTUPINFO structure. These are different flags, CREATE_NO_WINDOW should not be in STARTUPINFO.
You have to pass the CREATE_NO_WINDOW flag, then the console window won't show. Originally I've answered that you have to redirect the standard handles which is not correct (but still highly recommanded).
Set STARTF_USESTDHANDLES and fill in appropriate handles. If you are interested in the output of the process, create pipes, otherwise you can just open nul an pass that.
Try Using ProcessBuilder. Here is an example of some code that I have that seems to work just fine. In my code below, the shellScript is a StringBuilder that I am dynamically creating that contains the command and it's parameters that I want to execute.
String[] scriptArray = shellScript.toString().split(" ");
ProcessBuilder builder = new ProcessBuilder(scriptArray);
File outputFile = new File("/logs/AgentOutputLog.txt");
File errorFile = new File("/logs/AgentErrorLog.txt");
builder.redirectOutput(outputFile);
builder.redirectError(errorFile);
Process process = builder.start();
int errCode = process.waitFor();
//errCode = 0 means online
if(errCode == 0){
success = true;
break;
//errCode = 1 means offline
} else if (errCode == 1){
success = false;
break;
}
I have a pre-compiled exe (native C++11) which crashes (access violation error) at some point in iterative process. I can not afford debugging it and re-compile it again for now.
I thought of a dirty solution. I will make another program that is responsible for executing that exe and when it stopped working, I simply re-execute it again.
Is it possible? How can I know that the program was stopped?
Note: I am on Windows and doing development using MSVS.
I have found a solution with help of #Richard Hodges.
Make a new program with the this code:
#include <Windows.h>
#include <string>
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int main(int argc, const char**argv) {
while (true) {
TCHAR ProcessName[256];
STARTUPINFO si;
PROCESS_INFORMATION pi;
wcscpy(ProcessName, L"FaultyProgram.exe");
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
if (!CreateProcess(NULL, // No module name (use command line)
ProcessName, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return 0;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
return 0;
}
And the most important part is to disable UI Error message when a program crash by changing this value in the registry:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Windows Error Reporting
"DontShowUI"=dword:00000001
instead of:
"DontShowUI"=dword:00000000
This question already has an answer here:
CreateProcess method ends up with an error
(1 answer)
Closed 6 years ago.
I was reading about CreateProcess function in c++ and I wanted to try it. Basic idea of the code is to have my main execute another process (notepad). Really, it’s just the basic code. When I run the program, I get:
First-chance exception at 0x752bb763 in createprocess.exe: 0xC0000005: Access violation writing location 0x00be57b8.
Unhandled exception at 0x752bb763 in createprocess.exe: 0xC0000005: Access violation writing location 0x00be57b8.
When I make a break point for where the error occurs, I get taken to tidtable.c (which is for accessing threads, I guess).
Specifically in tidtable.c at CRTIMP PFLS_GETVALUE_FUNCTION __cdecl __set_flsgetvalue()
I really don’t know what or how to avoid this problem. The error occurs with the CreateProcess call (ie, it never outputs the “out of create”).
My code is:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <strsafe.h>
#include <direct.h>
#include <string.h>
#include <conio.h>
int main(VOID)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
//allocate memory
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
fprintf(stderr, "This is just a test");
//create child process
if (!CreateProcess(NULL,
L"C:\\Windows\\Notepad.exe",
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi))
{
fprintf(stderr, "create process failed");
return -1;
}
fprintf(stderr, "out of create");
//parent waits for child to complete
WaitForSingleObject(pi.hProcess, INFINITE);
fprintf(stderr, "after wait");
printf("Child Complete");
//close handle
CloseHandle(pi.hProcess);
// CloseHandle(pi.hthread);
}
If anyone knows how to overcome this problem, your help would be appreciated.
The problem is that the second parameter of the CreateProcess function is an in/out parameter.
If you specify it as a string like you did, it is a constant string and the function when it is called cannot write to the memory location, thus you have a memory access violation. The correct way is to call your function like this:
LPTSTR szCmdline = _tcsdup(TEXT("C:\\Windows\\Notepad.exe"));
//create child process
if (!CreateProcess(NULL,
szCmdline,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi))
{
fprintf(stderr, "create process failed");
return -1;
}
You may also want to read this blog article.
The 2nd arg to CreateProcess cannot be const or a literal string because the func attempts to modify the string. Copy the literal to a local array and then pass that as the 2nd arg.
I am launching Chrome with the app="http://..." parameter (a Chrome application shortcut) via C++. Now it seems to open with a size of roughly 400x800 which is crazy. I'd like to open it maximized or at least have it remember the size.
Is there a way to achieve this?
If you don't mind using the default browser (which, in my opinion, is the best option) instead of forcing the use of Chrome, you can simply open your URL with ShellExecute specifying that you want the window to be maximized:
#include <windows.h>
#include <Shellapi.h>
// requires linking towards Shell32.lib
// ...
if(ShellExecute(NULL, "open", "http://www.stackoverflow.com", NULL, NULL, SW_SHOWMAXIMIZED)<=32)
{
/* an error occurred */
}
I must open Chrome, and I have its path known in a variable. I also need to specify one parameter. Is this a problem?
Well, in this case it's better to use CreateProcess:
#include <windows.h>
// ...
// Assuming that the path to chrome is inside the chromePath variable
// and the URL inside targetURL
// Important: targetURL *must be* a writable buffer, not a string literal
// (otherwise the application may crash on Unicode builds)
PROCESS_INFORMATION processInformation;
STARTUPINFO startupInfo;
memset(&processInformation, 0, sizeof(processInformation));
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.wShowWindow = SW_SHOWMAXIMIZED;
BOOL result= CreateProcess(chromePath, targetURL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation);
if(result)
{
WaitForSingleObject( processInformation.hProcess, INFINITE );
CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );
}
else
{
// An error happened
}
Notice that you can try to specify a default size/posizion for the window using the dwX/dwY/dwXSize/dwYSize members of the STARTUPINFO structure, but I'm not sure if Chrome respects these settings.
--start-maximized should do the trick.
Taken from http://peter.sh/experiments/chromium-command-line-switches/
Haven't tested it myself though..