I assume you are talking about Windows as you are talking about spawnl?
So, do you mean a way that uses a CRT function, like spawnl, exec, ... (or rather _spawnl, _exec to give then their current name [1]), rather than a Win32 call?
(Out of curiousity, what have you against CreateProcess? After all, it would normally be the neatest solution.)
None of the spawnl, exec, ... family of functions have a flag equivalent to CreateProcess's CREATE_NEW_CONSOLE.
But, if you just cannot use CreateProcess, then there is this
hack. Note that the code is (probably) VC++ specific as it stands; you might need to tweak it if you use MinGW g++, etc.
Andy
[1] The names of spawnl, exec, ... were altered to _spawnl, _exec, ... in VC++ 2005 to indicate they are POSIX non-conformant. The old names are still exposed by a macro, but you should be warned that the non-_ name is deprecated. (The POSIX spawn functions all start with posix_ -- posix_spawn, ...)
Launcher program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include<iostream>
#include<cstdio> // Edit g++ need these two includes while VC++ (2008)
#include<cstdlib> // lets you forget to include them explictly :-(
#include<process.h>
// Persuade _spawnl to run a command line app in a
// new a new console window.
//
// It does this by running cmd.exe like this:
//
// cmd.exe /s start cmd.exe /c your_program.exe arg1 arg2 ...
//
// - the first cmd.exe is told to run the start command
// with the arguments
//
// cmd.exe /c your_program.exe arg1 arg2 ...
//
// - the second cmd.exe runs the target with
//
// your_program.exe arg1 arg2 ...
//
// Notes:
// - for info about cmd.exe, use "cmd /?" at the command line,
// or google it
// - should use full paths in real code, for safety.
// - the third "comspec" in the call to _spawnl is
// down to the way the function handles args; cmd.exe
// is invoked just the twice
// - the use of getenv() to find out where to find cmd.exe
// is not safe; but you shouldn't assume it's in C:\WINDOWS\system32
// either (unless the app is for solely your use)
int main()
{
std::cout << "Start hello.exe...\n";
const char exepath[] = "C:\\Test\\hello.exe";
// get COMSPEC, usually (but not always)
// C:\Windows\System32\cmd.exe"
char* comspec = getenv("COMSPEC");
_spawnl( _P_NOWAIT // flags
, comspec // cmd line
, comspec // arg[0] to main (of target)
, "/c" // arg[1]
, "start" // etc (see note above)
, comspec
, "/c"
, exepath
, "one"
, "two"
, "three"
, NULL );
std::cout << "<return> to continue...";
std::cin.get();
return 0;
}
|
Test program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// hello with arg handling
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Hello world!\n\n");
printf("argc = %d\n", argc);
for(int i = 1; i < argc; ++i)
printf("argv[%d] = %s\n", i, argv[i]);
printf("\n");
printf("<return> to continue...");
getchar();
return 0;
}
|