c++ system() orphan & zombie processes - c++

I have a little application, let's call it "launch.exe". It is a c++ appl.
What I do in it is I call system() 3 times to launch 3 other applications. let's call these A, B, and C.
problem #1
A, B, and C are GUI apps and "launch.exe" is not able to progress until A exits. Then it is stuck again until B exits. Then stuck again until C exits. I would like lauch.exe to be able to progress while the applications I have opened remain open.
Problem #2
Assuming that I am able to figure out a solution to problem #1, after A, B, and C are launched, I don't want "launch.exe" to stay open. I want launch.exe to close and I want A, B, and C to remain running.
Here is a scenario for you. Lets us say "launch.exe" only starts one application (let us call it A). Then, after A is started, if i close "launch.exe", A remains open.
OK...this is what I want but what just happened? Is A an orphan now? And if so, is this a problem?
And what if I closed A before I exited launch.exe? On the surface it seems OK, but what does it return to? If I launched an exe in cmd shell, it would return to that, but since I did it from a system() call in a c++ appl, does it return to my lauch.exe or does it become a zombie?
NOTES:
Why am I useing system()?
--Cause I need something that is Windows/Linux compatible.
--Cause I need to elevate privileges to admin level for some of the applications being launched.
--I should add that it is vital that A, B, and C be totally independent (for security reasons they should not share the same memory space or anything else).
--Last, some of the apps, B, and C are multi-threaded (I state this because I have read that some functions do not spawn multi-threaded applications properly. I'm not clear on reasons why.).

Use spawn instead, this won't block the launcher until the child exits.
Or, since you're already using Qt, use QProcess.
There is no portable way to spawn a subprocess as a different user, but the Windows-specific way is CreateProcessWithLogonW.

Why don't you start your A B C processes with ampersand "&" appended to command parameters
std::system ("ProcessA&");
std::system ("ProcessB&");
std::system ("ProcessC&");
This way your launcher will not wait for these processes to exit.
Then exit your launcher with QApplication::exit or QApplication::quit
Read this SO question to see the difference between fork/execvp and system().

Related

How to run multiple shell command at the same time in linux

I am trying to run multiple command in ubuntu using c++ code at the same time.
I used system() call to run multiple command but the problem with system() call is it invoke only one command at a time and rest commands are in waiting.
below I wrote my sample code, may this help you to get what I am trying to do.
major thing is I want to run all these command at a time not one by one. Please help me.
Thanks in advance.
main()
{
string command[3];
command[0]= "ls -l";
command[1]="ls";
command[2]="cat main.cpp";
for(int i=0;i<3;i++){
system(command[i].c_str());
}
}
You should read Advanced Linux Programming (a bit old, but freely available). You probably want (in the traditional way, like most shells do):
perhaps catch SIGCHLD (set the signal handler before fork, see signal(7) & signal-safety(7)...)
call fork(2) to create a new process. Be sure to check all three cases (failure with a negative returned pid_t, child with a 0 pid_t, parent with a positive pid_t). If you want to communicate with that process, use pipe(2) (read about pipe(7)...) before the fork.
in the child process, close some useless file descriptors, then run some exec function (or the underlying execve(2)) to run the needed program (e.g. /bin/ls)
call (in the parent, perhaps after having got a SIGCHLD) wait(2) or waitpid(2) or related functions.
This is very usual. Several chapters of Advanced Linux Programming are explaining it better.
There is no need to use threads in your case.
However, notice that the role of ls and cat could be accomplished with various system calls (listed in syscalls(2)...), notably read(2) & stat(2). You might not even need to run other processes. See also opendir(3) & readdir(3)
Perhaps (notably if you communicate with several processes thru several pipe(7)-s) you might want to have some event loop using poll(2) (or the older select(2)). Some libraries provide an event loop (notably all GUI widget libraries).
You have a few options (as always):
Use threads (C++ standard library implementation is good) to spawn multiple threads which each perform a system call then terminate. join on the thread list to wait for them all to terminate.
Use the *NIX fork command to spawn a new process, then within each child process use exec to execute the desired command (see here for an example of "getting the right string to the right child"). Parent process can use waitpid to determine when all children have finished running, in order to move on with the program.
Append "&" to each of your commands, which'll tell the shell to run each one in the background (specifically, system will start the process in the background then return, without waiting for the result). Not tried this, don't know if it'll work. You can't then wait for the call to terminate though (thanks PSkocik).
Just pointing out - if you run those 3 specific commands at the same time, you're unlikely to be able to read the output as they'll all print text to the terminal at the same time.
If you do require reading the output from within the program (though not mentioned in your question), this is relevant (although it doesn't use system).

C++ stop other programs by PID on brute force quit from client

I have an .exe Program, which triggers some other files during execution.
So at a given point, the tree might become like:
Main program
-Program 1
-Program 2
-Program 3
Of all these programs I have their PID, so I am able to close them successfully. However, when a user 'brute forces the program' (read close the program manually), I am unable to close these child programs. Is there an option to trigger the closing of child-programs before the main-program itself will actually exit. (Something is for example also possible in an html-page to remind the user e.g. or they really want to leave te page).
Because, when this situation occurs, on the next run the main-program will try to start up these child-programs again, however they are already running. (And the settings of the main-program are time dependent and have to be transferred to the other child-programs on start-up to work properly)
Ideally, I would like to have a cross-platform solution, since I have to make the app available for Windows, Linux and MacOS.
Thanks for your answers.
This is an OS feature and each OS offers it in its own way. Keeping track of the PIDs does not work, for once for the reason you mention (your parent process may itself crash) and second because the child process may spawn grand-children processes of its own that needs to be tracked, and then grand-grand-children and so on.
On Windows this is handled by NT Job Objects by asking for the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE:
Causes all processes associated with the job to terminate when the last handle to the job is closed.
The way to use it is to create the job object in the parent process and make the handle non-inheritable. Then any child process will become part of the job, but only one handle exisst (the one owned by the parent). If the parent crashes then the handle is reclaimed by the OS and this will terminate the NT job object, killing all child processes as well as any grand-child or grand-grand-child process.
On Linux (and OS X) the same functionality is achieved with process groups.
I am not aware of any cross-platform library that would abstract this into a coherent uniform API.

Run a Exe from another exe

I want to execute one exe from another exe. but the other exe can not run if first exe is running.
So i want to run the exe and exit from the application before the second exe gets executed.
Any help on this.
Consider a third application, which you launch from your first app. The third one checks to be sure the first one has terminated, then launches the second app and terminates itself. I have had to do this in the past; it works fine.
I am not sure exactly how it is done in Windows, but I think that the general guidelines are the same between linux and windows:
You need to fork a child process, in Linux this is done using fork() function, in Windows I think you can use CreateProcess().
In this child process, you need to call one of the exec functions which changes the code of this child process to the code of any executable that you can specify as a parameter to the exec function.
The code, thus, should be something like this pseudo-code:
c= CreateProcess()
if (c == child)
{
exec("My other executable.exe")
}
This is the general procedure, but you need to figure out the syntax
You are going to need a process to sit in the middle if you are not allowed to have the two main processes executing simultaneously. Which means that you need three processes in total. The two main processes, A and C, and the broker in the middle, B. Here's how it goes down:
Process A executes.
Process A starts process B passing in its process
handle.
Process A terminates.
Process B waits on process handle for process A. That becomes signaled when process A has terminated.
Process B starts process C.
Process B terminates.
I'm assuming that you already know how to create processes, pass arguments to process, duplicate handles, wait on handles and so on.

In c++, not waiting doesn't mean running in the background?

In my c++ program, I try to run programs in the background by simply not waiting for them.
However in Linux, if I start vi in the background like this: vi &, then vi doesn't show up. In my program, vi will still pop up even if I don't wait for it to terminate.
So does that mean that I'm not really running it in the background? How can this be fixed?
Also, I noticed that in Linux if I type fg to bring vi into the foreground, then vi will appear. How can I do this in c++?
What's going on here is rather complicated (for more information than you probably require, see glibc's manual section on job control) but the short version is: Only the foreground process group can access the terminal. Any other process gets automatically ^Zed by the kernel if it tries to access the terminal.
When you fork a process from C, if the parent is in the foreground process group, the child is also considered to be in the foreground process group unless either the parent or the child changes that. When you do vi &, the shell (which is just another C program, remember) takes vi out of the foreground process group. But you're not doing that, so vi runs immediately.
Now, you want to fork a process from your C program and have it be treated the same as if it had been run with & from the shell. You can only do part of that. You can put it into a non-foreground process group -- see the glibc manual for instructions; as I said, it's complicated -- but you can't add it to the list of process groups that the shell's job control commands know about. That list is state internal to the shell, there's no way to get at it from another process.

Is it possible to kill a C++ application on Windows XP without unwinding the call stack?

My understanding is that when you kill a C++ application through Task Manager in Windows XP, the application is still "cleanly" destructed - i.e. the call stack will unwind and all the relevant object destructors will be invoked. Not sure if my understanding is wrong here.
Is it possible to kill such an application immediately, without unwinding the stack?
For example, the application may employ RAII patterns which will destroy or release resources when an object is destructed. If the traditional "kill process" through Task Manager is graceful, providing a way to kill the application immediately would allow me to test ungraceful shutdown (e.g. a power outage).
Edit:
Just to clarify, I was after an existing utility or program that would allow me to do this. I should be able to use the solution on programs that I don't have the source code for, meaning that a programmatic solution is not really acceptable.
Edit:
Just to provide more context, sometimes I have to work with 3rd party services which are very intrusive (e.g. nagging me to reboot every hour). Since I know that I don't need to reboot, I want to kill the process/service so it doesn't nag me anymore. Unfortunately some of the 3rd party developers were "smart" enough to prevent me from doing this, and when I kill the process through Task Manager, the system will reboot immediately (I'm guessing that are using RAII to achieve this).
I believe task manager tries a "nice" shutdown by sending a WM_CLOSE message, then if the application doesn't respond it's killed.
This call should kill the process immediately with no warning:
TerminateProcess
e.g.:
TerminateProcess(GetCurrentProcess(), 1);
Update:
You may find this article interesting:
Quitting time: exiting a C++ program
Update 2:
I should be able to use the solution on programs that I don't have the source code for
Hmm, well this is undesirable behavior 99.9% of the time.
SysInternals has a utility called pskill:
http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx
but I'm not sure how "nice" it is.
You might need to roll your own, but it should be pretty easy:
DWORD pid = <get pid from command line>;
TerminateProcess(OpenProcess(PROCESS_TERMINATE, FALSE, pid));
The standard Windows way to do this, without relying on 3rd-party tools, is to use taskkill /f:
taskkill /f <process-id>
taskkill /f /im <process-executable-name>
/f means "force" here, and ensures that process is terminated unconditionally and immediately, with no query or warning.
Unless I'm terribly mistaken (and I just did a little testing to confirm), Task Manager tries to close programs in different ways depending on which tab you're using. If going through the Applications tab and pressing End Task, it will try to close the program cleanly by first sending a WM_CLOSE. But if going through the Processes tab and pressing End Process, it seems to use something along the lines of TerminateProcess, which means no stack unwinding and such.
So first, if you aren't using End Process on the Processes tab, try that.
If that's what you already tried and their software still manages to reboot the system somehow, then there is something more complicated going on. Other people may be on the right track about there being additional processes.
I believe the C standard library method exit(0); will do exactly that, abort the program without calling any destructors, deallocators, etc.
Try that, and let me know if it meets your needs?
It looks like abort() will give you an abnormal exit.
ANSI 4.10.4.1 The behavior of the abort function with regard to open and temporary files
The abort function does not close files that are open or temporary. It does not flush stream
buffers
[source]
and
Abort current process
Aborts the process with an abnormal program termination.
The function generates the SIGABRT signal, which by default causes the program to terminate >returning an unsuccessful termination error code to the host environment.
The program is terminated without executing destructors for objects of automatic or static
storage duration, and without calling any atexit function.
The function never returns to its caller.
[source]
I would try PSKill as suggested by Tim above. I would guess that this will fail as well. If the 3rd party services are really serious about avoiding death, then the service definition may be set to "reboot on crash". The other common approach is to have another service that watchdogs the primary one. The primary service usually sets a global event or employs some other notification mechanism that the watchdog service watches. If the primary service doesn't notify the watchdog, then the watchdog restarts the computer.
The aptly named Kill Tool, available from Microsoft Download. Is part of the Windbg suite also.
The Kill tool, kill.exe, terminates
one or more processes and all of their
threads. This tool works only on
processes running on the local
computer.
kill /f <process>
For example, kill /f lsass (just kidding, do not kill LSA!).
If you want to roll your own, TerminateProcess is the way to go.
The C function abort() in the standard library will instantly kill your application with no cleanup.
C++ defines a standard global function terminate(). Calling it will also instantly exit your application.
Technically terminate()'s behavior could be overridden by the set_terminate function. It calls abort by default.
There are utilities around that can forbid reboot.
HideToolz does that for example -- there is a checkbox buried somewhere that will make it ask you when something initiates reboot. It is detected by many antiviruses as rootkit (which it is, but this one is supposedly tame), so it might be probematic to run on systems you don't have full control over (when antivirus mandated by domain policy, etc)
Extending Pavel's answer:
HANDLE launch(string filename, string params)
{
auto ftemp = wstring(filename.begin(), filename.end());
LPCWSTR f = ftemp.c_str();
auto ptemp = wstring(params.begin(), params.end());
LPCWSTR p = ptemp.c_str();
SHELLEXECUTEINFO ShRun = { 0 };
ShRun.cbSize = sizeof(SHELLEXECUTEINFO);
ShRun.fMask = SEE_MASK_NOCLOSEPROCESS;
ShRun.hwnd = NULL;
ShRun.lpVerb = NULL;
ShRun.lpFile = f;
ShRun.lpParameters = p;
//ShRun.nShow = SW_SHOW;
ShRun.nShow = SW_HIDE;
ShRun.hInstApp = NULL;
if (!ShellExecuteEx(&ShRun))
{
//Failed to Open
}
return ShRun.hProcess;
}
void kill(string filename)
{
launch("taskkill.exe", "/f /im " + filename);
}
void main()
{
kill("notepad.exe"); //Kills all instance of notepad
}