Windows Parent and Child Process creation - c++

I want to create 5 child process in Windows using C++. But I am confused that CreateProcess asks for lpApplicationName and not like fork in which I can figure out whether I am child or parent. how to do this in Windows

Unfortunately the CreateProcess function can only be used to load a program and start a new process for that program.
You can however use CreateProcess to simulate the fork functionality, by asking it to load the program you are already running, and then ask it to jump to the correct position. This is what is (or was, at least) done by Cygwin, as referenced by this old answer.

It is usually preferable in Windows to use threading rather than multiple processes, because processes are much heavier objects in Windows than in UNIX.
However, you can do what you're asking by passing the name and path of your application to CreateProcess (using GetModuleFileName if you don't already know it) and including a command-line argument to tell your application that it is being launched as a child process.
Keep in mind that the child processes will be started from scratch, they will not have a copy of the parent's memory as they would if you were using fork.

Related

Possible to have Win32 application block until it exits?

When I open a command line in Windows (cmd) and start a program, for example calc, the prompt immediately returns and the program is started (the calculator window is displayed).
This is contrary to how I know it from the Linux world: when I start a (possibly with GUI) application, the prompt does not return until I exit the started program.
Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?
Possible to have Win32 application block until it exits?
Call CreateProcess to create the process. This will yield a handle to the process in the PROCESSINFORMATION struct that is returned. Pass that process handle to WaitForSingleObject to wait until the process is signaled.
Based on the comments it seems that what you really want is an executable that will behave like a console app when its parent process is a console app. And behave like a GUI app otherwise. It's not possible to do both from a single executable. The target subsystem is determined by metadata in the executable file.
The standard way to handle this is to have two executables, each targeting the different subsystems. One a console app, the other a GUI app. The common examples of this are java.exe and javaw.exe, python.exe and pythonw.exe.
Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?
I think there are a few questions here.
First, how do you create a process in Windows? To create a process Windows, you use CreateProcess.
Second, how does CreateProcess work? CreateProcess obviously creates a new process (like calc.exe), and it offers a lot of options to create the process. It also returns a BOOL to let you know if the call failed or succeeded.
In the case the call fails, you get a failure immediately. That's a "synchronous" failure, and you can continue moving along in your procedures.
In the case the call succeeds, your process is "detached" from the child. Its more like an "asynchronous" call to the function. You can synchronize with the child process, and you can learn that it has exited by waiting on the hProcess member of the PROCESS_INFORMATION structure.
Third, not everyone starts processes from the command line. It might be started by clicking it on the desktop. This is true in the Linux/X11 (et al) world too.
Fourth, from the Windows command line, I believe you can use CALL for other batch files. But I don't recall if it applies to programs, too.

Closing an application properly: an Alternative to TerminateProcess

I'm facing an issue with TerminateProcess() function.
The application I'm currently writing a JobScheduler app that schedules and launches job at a specific time.
For this purpose, I'm using CreateProcess() to execute my JobLauncher.
The JobLauncher process then launches a console program (using createprocess ) which effectively executes the job executable, waits for its termination and monitors the duration, user and kernel times elapsed etc.
In order to kill the job from the JobScheduler I firstly started using TerminateProcess() but it does not allow me to close the executable itself properly. I mean i found no way to hook any termination event.
Until I find a better way than a brutal TerminateProcess(), I wrote an intermediate solution using the GenerateConsoleCtrlEvent() in the calling program.
In the job application that launches the target job executable, I installed a handler using SetConsoleCtrlHandler().
And in the handler, I can terminate the process of the job and notifies my thirdparties properly.
This is the better solution I found for now.
Is there a better way to programmaticaly and properly close a process ?
Do you this solution is completly absurd ?
I'm not a "system-level" specialist developer though...
Z.
This well know Windows console problem and you can find some solutions here.
We used on internal console utility which has name "Kamikaze". It worked as described here and for me it's a best solution cause there is no problem with porting between Windows versions and Windows architectures (x86, x64).

Open a process from file, in C++ on Linux

I'm coding my application in C++ on Linux. C++ has a function called 'system' to execute a programme.
I try to open the gnome-system-monitor from C++ like this:
system("gnome-system-monitor");
However, the thread of my application blocks when I call this 'system' function until I close the window of gnome-system-monitor.
Any other ways to open a process from file without blocking the caller process?
The classic way, which works on any Linux or otherwise POSIX-based system, is
if (0 == fork()) {
execlp("gnome-system-monitor", "gnome-system-monitor", (char *)NULL);
}
(with error handling omitted from this example.) This (a) creates a new process, (b) in that new process, runs "gnome-system-monitor" after searching the PATH environment variable to find such a command, (c) passes it the name "gnome-system-monitor" as argv[0] and no other arguments. In the parent, once the new process is created it barrels on ahead without waiting for any result.
See the man pages for fork and execlp for more details.
fork/exec or posix_spawn. glib also has GSpawn if you are using that.
Gnome is built above GTk (which contains Glib), and you probably want the Glib Spawning Processes functions.
Of course, on Linux and Unix, processes are forked. Read a good book like
advanced unix programming and advanced linux programming to learn more about syscalls related to processes, notably fork(2), execve(2), pipe(2). Read also about the proc(5) filesystem.
Yes. Call System function on a separte thread.

Detecting child processes

Is there a way (in C++ & windows XP) to detect if one process spawns any other processes?
for example,
write.exe in system32 spawns wordpad.exe then disappears, is there a function that tells me if the process is about to do this?
for those interested i solved the problem using this section of msdn:
http://msdn.microsoft.com/en-us/library/aa390425(v=VS.85).aspx
Nothing in the Win32 API for this. However, it is supported through WMI with the Win32_ProcessStartTrace query. You'll find some C# code that demonstrates the query in my answer in this thread. Writing WMI code in C++ is fairly painful, you'll find a link to boilerplate code you have to write in the MSDN Library article.
Do beware that this isn't particularly fast. It isn't clear to me how much help the WMI provider gets from the kernel to generate the notification but given the speed it quacks like polling. In other words, the process is likely to be well on its way by the time you get the notification. This is otherwise par for the course on a multitasking operating system.
You can enumerate over the process tree, which identifies running processes and their parents. This is the inverse of what you want (you want to identify child processes, not parent processes). But of course by keeping track of parent process IDs while enumerating, you can identify which sub-processes a given process has spawned.
To do this, call CreateToolhelp32Snapshot and then use Process32First and Process32Next to enumerate the processes. The enumeration will fill in a PROCESSENTRY32 struct that contains a th32ParentProcessID member.
This is a polling method; there may be another way of actually hooking the CreateProcess function, but I don’t have any information about that.
I think you would need to make a global hook DLL that attaches itself to every running process. DLL then finds a place where a function call to CreateProcess is mapped to actual CreateProcess from kernel32, and change a table entry to redirect the call to it's own code to "detect" the call to CreateProcess. All this assuming that some user firewall will not prevent your global hook from executing.

How to interface with an executable in C++

I have an executable that I need to run some tests on in C++ - and the testing is going to take place on all of Windows, Linux and Mac OSes.
I was hoping for input on:
How would I interface with the previously built executable from my code? Is there some kind of command functionality that I can use? Also, since I think the commands change between OSes, I'd need some guidance in figuring out how I could structure for all three OSes.
EDIT - Interface = I need to be able to run the executable with a command line argument from my C++ code.
The executable when called from the commandline also ouputs some text onto a console - how would I be able to grab that ouput stream (I'd need to record those outputted values as part of my tests).
Feel free to ask me follow up questios.
Cheers!
If you use qt to develop your code, you'll find QProcess will allow you to spawn a command line program in a platform-agnostic way.
Essentially:
QObject *parent;
QString program = "yourcommandlineprogram";
QStringList arguments;
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);
You can then read from the process with various function calls such as readAllStandardOutput (), and write to the input of the process with QProcess::write(QString).
Alternatively, if you prefer Boost to Qt, Boost.Process will also let you launch processes. I confess I don't like the syntax as much...
boost::process::command_line cl("yourcommandlineprogram");
cl.argument("someargument");
boost::process::launcher l;
l.set_stdout_behavior(bp::redirect_stream);
l.set_merge_out_err(true);
l.set_work_directory(dir);
boost::process::child c = l.start(cl);
You can then work with your subprocess 'c' by using stream operators << and >> to read and write.
All those OSes support some form of "subprocess" calling technique, where your tester creates a new child process and executes the code under test there. You get to not only pass a command line, but also have the opportunity to attach pipes to the child process' standard input and output streams.
Unfortunately, there is no standard C++ API to create child processes. You'll have to find the appropriate API for each OS. For example, in Windows you could use the CreateProcess function: MSDN: Creating Processes (Windows).
See also Stackoverflow: How do you spawn another process in C?
As I understand, you want to:
Spawn a new process with arguments not known at runtime.
Retrieve the information printed to stdout by the new process.
Libraries such as QProcess can spawn processes, however, I would recommend doing it by hand for both Windows and MacOS/Linux as using QProcess for this case is probably overkill.
For MacOS/Linux, here's what I would do:
Set up a pipe in the parent process. Set the read end of the pipe to a new file descriptor in the parent.
fork.
In newly created child process, set stdout (file descriptor #1) to the write end of the pipe.
execvp in the newly created child process and pass the target executable along with what arguments you want to give it.
From the parent process, wait for the child (optional).
From the parent process, read from the file descriptor you indicated in Step 1.
First of all, is it possible that you simply need to want to make your original code reusable? In that case you can build it as library and link it in your new application.
If you really want to communicate with another executable then you can need start it as a subprocess of the main application. I would recommend the Process class of the Poco C++ libraries.
Looks like a job for popen(), available on Linux, Windows, and OS X
Sounds like you are only planning to do functional testing at the executable level. That is not enough. If you plane to do thorough testing, you should also write unit tests. For that there is some excellent frameworks. My prefered one (by far) for C++ is BOOST::Testing.
If you control source code there is also common tricks for functional testing beside launching exe from an external process : embed functional tests. You just add an option to your program that execute tests. This is cool because tests are embedded in code and autocheck can easily be launched in any execution environment.
That means that in the test environment, as you call your program with some test dedicated arguments, nothing keeps you from going the full way and redirect the content of stdout and even check the tests results from within the program. It will make the whole testing much easier than calling from an external launcher, then analysing the results from than launcher.