Launch console app from console apps - c++

I am using this piece of code to launch a process from a GUI app. but, according to the notes of this code it is not possible to launch a process from a console app. actually i want to do that, I want a console app to launch another console process, please do you have any idea how to do that?
// This technique must be used for "console-less" parents such as GUI
// applications or detached applications.
// Using the STARTUPINFO STARTF_USESTDHANDLES flag, requires that
// the CreateProcess fInheritHandles parameter be set TRUE so that
// the file handles specified in the STARTUPINFO structure will be
// inherited by the child.
// setup the child process's handles for stdin, stdout, & stderr.
STARTUPINFO childProcStartupInfo;
memset( &childProcStartupInfo, 0, sizeof(childProcStartupInfo));
childProcStartupInfo.cb = sizeof(childProcStartupInfo);
childProcStartupInfo.hStdInput = hFromParent; // stdin
childProcStartupInfo.hStdOutput = hToParent; // stdout
childProcStartupInfo.hStdError = hToParentDup; // stderr
childProcStartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
childProcStartupInfo.wShowWindow = SW_HIDE;
// Now create the child process, inheriting handles
PROCESS_INFORMATION childProcInfo; /* for CreateProcess call */
bOk = CreateProcess(
NULL, // filename
pCmdLine, // full command line for child
NULL, // process security descriptor */
NULL, // thread security descriptor */
TRUE, // inherit handles? Also use if STARTF_USESTDHANDLES */
0, // creation flags */
NULL, // inherited environment address */
NULL, // startup dir; NULL = start in current */
&childProcStartupInfo, // pointer to startup info (input) */
&childProcInfo); // pointer to process info (output) */

did you try shellexecute? I think that works..

You can try:
ShellExecute(), ShellExecuteEx(), CreateProcess(), system(), _wsystem().
There are a few more, but one of these got to work for you!
Personally, I would go with CreateProcess and than wait for the process to quit (found on google this example: http://www.codeproject.com/Tips/333559/CreateProcess-and-wait-for-result). Notice that system()/_wsystem() are the easiest to use, but if you're not careful they can be exploited !!!
Hope it helps! :-)

Try this code:
#include <Windows.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* app_to_launch=new char[80];
strcpy(app_to_launch,"app.exe");
STARTUPINFO si;
PROCESS_INFORMATION pi;
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)
app_to_launch, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // 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() );
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return 0;
}

Related

Process of c++ executable doesn't close correctly

in my program I start other c++ application in the same window closing the previous. Sometimes the process that I see in the Task Manager doesn't close. So I'll have many process whit the same name. How can I avoid this?
startup("../folder/c++_executable.exe");
exit(0);
void startup(LPCTSTR lpApplicationName)
{
// additional information
STARTUPINFO si;
PROCESS_INFORMATION pi;
// set the size of the structures
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// start the program up
CreateProcess( lpApplicationName, // the path
"", // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // 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
;
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
I think you will need to check why it's not closing - get VisualStudio/WinDBG and attach to process that is not closing and check where it hang.

How to execute external programm in the parent C++ programm in Windows?

int system(const char *str);
declared in stdlib.h
As I know, this code will spawn a new process not within parent process and in Task Manager will be two processes - parent and child.
How to spawn child process in the parent process? ie in Task Manager must be only one - parent - process.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // 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;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
Source: MSDN

CreateProcess not in primary thread

I use CreateProcess() to start a other programm from my C++ code.
The helppage says that it
Creates a new process and its primary thread. The new process runs in the security context of the calling process.
I would like to have it in his own thread, so the application would keep on going. Is there any simple way to do so? I am not familar with boost and Co.
My code:
bool startup(LPWSTR lpApplicationName)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
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)
lpApplicationName, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // 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 false;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return true;
}
and how to call the function:
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t path[] = L"C:\\path\\to\\paridise.exe";
startup(path);
}
Transforming the comment by ElderBug in a reply
The problem in your code is the presence of an infinite wait after the CreateProcess call:
WaitForSingleObject( pi.hProcess, INFINITE );
Just comment it and the program execution will not stop.
I also did this same error and I stumbled in this SO question; the fact is that many of us get the code from the MSDN example here (without much attention), which has in fact this infinite wait.

CreateProcess function issue

I'm trying to start an process from my code with createprocess function. The command line is ok, and the other exe, i can start it without problems from visual studio.
When I am trying to start it from the other process with createprocess it gives me - Runtime error this app has requested the runtime to terminate it in an unusual way.
What could be the problem ? How could I remove this problem ?
STARTUPINFO si;
PROCESS_INFORMATION pi;
bool bResult;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
//Cast System::String* __gc to char*
char* chAppName = (char*)(void*)Marshal::StringToHGlobalAnsi(AppName);
char* chCmdLine = (char*)(void*)Marshal::StringToHGlobalAnsi(CmdLine);
//Start the child process.
bResult = CreateProcess( chAppName, // No module name (use command line)
chCmdLine, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // 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
Try eliminating the StringToHGlobalAnsi calls and hard coding them instead first. If that stops the problems, we can then sort out the StringToHGlobalAnsi calls.

Launching an application from a thread with C++

I need to launch a 3rd party program inside a thread, wait to get the results both from stdout/stderr with C++.
What methods are available?
Are they cross-platform? I mean, can I use them both for cl/gcc?
On Unix:
http://linux.die.net/man/3/execl
#include <sys/types.h>
#include <unistd.h>
void run_process (const char* path){
pid_t child_pid;
/* Duplicate this process. */
child_pid = fork ();
if (child_pid != 0){
/* This is the parent process. */
int ret = waitpid(child_pid, NULL, 0);
if (ret == -1){
printf ("an error occurred in waitpid\n");
abort ();
}
}
else {
execl (path, path);
/* The execvp function returns only if an error occurs. */
printf ("an error occurred in execl\n");
abort ();
}
}
On Windows:
http://msdn.microsoft.com/en-us/library/ms682425%28v=vs.85%29.aspx
# include <windows.h>
void run_process (const char* path){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
bool ret = = CreateProcess(
NULL, // No module name (use command line)
path, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
false, // Set handle inheritance to FALSE
0, // 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
)
if (!ret){
printf("Error");
abort();
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
system should be platform independant, but you might want to stick with createprocess (win)/ exec (others) if there is a concern about running the program with the same security privledges.
There is a set of posix functions to launch an external executable - see exec - which are cross platform. To do some specific tasks on windows you may need to use windows specific createprocess.
These generally block so you would have to start them in a new thread. Threading is generally not cross platform, although you can use posix (pthreads) on windows.
An alternative is to use somthing like Qt or wxWidgets cross platform libraries.