execve from a Mac OS X launchd daemon - c++

Is it possible to use execve from a launchd daemon? My process that I would like to make into a daemon launches several child processes using fork() followed by execve, but the documentation for creating launchd daemons states that "calling fork followed by exec" is not ok. Does this mean that I cannot create child processes from a daemon?

AFAIK, you can fork and exec just fine. The critical point is this one: "You must not fork your process and have the parent process exit." Thing is, launchd "watches over" your service. If your service exits, it gets restarted. That means it may not daemonize, either (with daemonize I mean the classical spawn a new process, create a new process group, exit parent process, subprocess lives on scheme).
I guess you should make sure to kill/quit your subprocesses before you exit the main process, just to not litter the environment.

Related

Kill all the child processes when parent is killed

I'm running a C++ program under LINUX.
From my program's code I'm calling another program with a system() call:
system("calledProgram opt1 opt2 ... opt_n");
But this calledProgram runs with multiple processes (with a specific names, say p1, p2, p3, p4).
How can find and kill these processes when my program is being killed externally by the user.
Here (How to kill process in c++, knowing only part of its name) described how to find processes with a specific name and kill them.
But what if user runs the program with the same options from different directories. Should I check for the running directory also to find correct processes?
Is there another (better) way to kill those child processes?
PS: When I'm running calledProgram from the cmd line, and then, killing it by ctrl+c, its processes are not being killed automatically.
I recommend you to use fork/exec instead of system() to call your new program.That's easy.See this.
It seems necessary for your application since you need "calledProgram" to be child of your program so it'll die when someone kills your program.
You also need to handle SIGINT signal. In the most simple way you need something like this:
#include<signal.h>
void signal_handler()
{
kill(0,SIGTERM);
}
int main()
{
signal(SIGINT,signal_handler);
}
When killing a process all child processes are killed.
This is true for child processes that has not detached.
Your process only has to remember the pids of it's nearest children and kill them. The childrens child processes will automatically die.
If you put all child processes in the same process group, you can kill all with a single kill(2) call.
See: man 2 kill

Restarting a linux daemon

I have Linux daemon that I have written in C++ that should restart itself when given a "restart"-command from a user over the network through its console. Is this possible? I use a /etc/init.d script. How can I program it to restart itself? Should I launch a new process with a very long delay (one minute) that then fires the shell script again ? Problem is that the daemon may take a very long time to close down and it could take even more than a minute in a worst-case scenario.
There are basically three ways for an application to restart itself:
When the application is told to restart, it does proper clean-up, releases all resources it has allocated, and then re-initializes like it was started from scratch.
Fork a new process, where the new child process execs itself and the parent process exits normally.
The daemon is actually just a wrapper application, much like an init-script. It forks a new process which runs the actual application, while the parent process just waits for it to exit. If the child process (and the real application) returns with a special exit-code, it means that it should be restarted so the forks/execs all over again.
Note that points 2 and 3 are basically the same.
Break down the restart as two steps, stop and start. if your program takes time to stop, it should be handled in the stop function, I can't comment on specifics since I don't know your usecase, but I'd imagine monitoring the process to check if it's terminated will be a graceful way to stop
Do whatever shut-down/clean-up you need to do, then call this:
execl( argv[0], argv, reinterpret_cast< char* >( 0 ) );
Just like fork() and exec(), but skipping the fork. The exec will replace the current process with a new copy of itself. cf. http://linux.die.net/man/3/exec
Your init script should just kill your daemon and start it again. Don't try to restart your daemon FROM your daemon.

C++ process management: WinAPI "SetProcessShutdownParameters " in Linux?

In Windows (7), in VC++ we can set the "process shutdown parameters" (in XP a parent process will automatically shutdown before the child) to ensure a parent process is killed BEFORE a child process, like so:
GetProcessShutdownParameters(&shutdownlevel, &shutdownflags);
SetProcessShutdownParameters(shutdownlevel+1, SHUTDOWN_NORETRY);
How to do this in C++ on Linux (gcc) ? I find a lot discussion in many forums on how to ensure a child process killed, in case a parent process dies (e.g. use of prctl on Linux), but I have found nothing on how to GUARANTEE that the parent process is killed by the OS before the child process, like the above for Windows. Maybe it is automatic in Linux ?
System shutdown in the Unix world works a bit differently.
When the system is being shut down, at first the shutdown scripts are invoked, which handle any complex or time consuming tasks, and when the scripts have run, all remaining processes are then first sent a SIGTERM signal (which kills any process that doesn't have an explicit handler), and, a few seconds later, a SIGKILL signal (which kills the process and cannot be handled).
The order in which the last part happens is undefined.
In general programs should be written so they can be shutdown by simply sending SIGTERM.
I'm guessing that you want the parent stopped before the child because the parent would simply restart the child. The proper way to avoid that is to collect the child's exit status (which you are responsible for anyway), and avoid restarting when the exit status indicates that the process ended because of being sent SIGTERM.
(You still want to restart on SIGKILL, because that is what happens to the largest process when the system runs out of memory)

Make child process spawned with system() keep running after parent gets kill signals and exits

In a Linux/C++ library I'm launching a process via the system() call,
system("nohup processName > /dev/null&");
This seems to work fine with a simple test application that exits on it's own, but if I use this from inside of a Nodejs/V8 extension which gets a kill signal, the child process gets killed. I did find that running,
system("sudo nohup processName > /dev/null&");
With the sudoers file set up to not require a password manages to make this run even when the parent process (node) exits. Is there someway to entirely detach the child process so signals sent to the parent and the parent exiting have no effect on the child anymore? Preferably within the system() call and not something that requires getting the process ID and doing something with it.
The procedure to detach from the parent process is simple: Run the command under setsid (so it starts in a new session), redirecting standard input, output and error to /dev/null (or somewhere else, as appropriate), in background of a subshell. Because system() starts a new shell, it is equivalent to such a subshell, so
system("setsid COMMAND </dev/null >/dev/null 2>/dev/null &");
does exactly what is needed. In a shell script, the equivalent is
( setsid COMMAND </dev/null >/dev/null 2>/dev/null & )
(Shell scripts need a subshell, because otherwise the COMMAND would be under job control for the current shell. That is not important when using system(), because it starts a new shell just for the command anyway; the shell will exit when the command exits.)
The redirections are necessary to make sure the COMMAND has no open descriptors to the current terminal. (When the terminal closes, a TERM signal is sent to all such processes.) This means standard input, standard output, and standard error all must be redirected. The above redirections work in both Bash and POSIX shells, but might not work in ancient versions of /bin/sh. In particular, it should work in all Linux distros.
setsid starts a new session; the COMMAND becoming the process group leader for its own process group. Signals can be directed to either a single process, or to all processes in a process group. Termination signals are usually sent to entire process groups (since an application may technically consist of multiple related processes). Starting a new session makes sure COMMAND does not get killed if the process group the parent proces belongs to is killed by a process-group wide signal.
My guess is that the whole process group is being killed. You could try setpgid in the child to start a new process group. The first step should be to get rid of system and use fork and execve or posix_spawn.

is it is possible to run a background process if the window is closed?

I am creating an application in C++ gtk and if I press a button a threading process will start and I need to run the application if the window is closed also is it possible?
Under a Unix system (and since Windows 10), you create another process using the fork() function. To run a program you then use the execve() or similar.
However, that means you need to communicate with that other process using a pipe (see pipe() or pipe2()) or via the network.
Using a thread instead of a process allows you to run in the same memory & process and you can very easily shared everything between multiple threads.
As far as I know, the gtk loop just returns once the user selects the "Close Window" or similar exit function. It would be up for your main() function to make sure that it waits for all the threads to be done before exiting. For threads, this is usually done with a "join()". It will depend on the library you use to run your background process.
Note that in most cases people expect processes to exit whenever they ask the process to exit. Showing a window saying that your process is still running in the background (is busy) is a good idea for a process which runs a GUI. Especially, if you run your process from the console, it would not exit immediately after you closed the window, so letting the user know what's happening is important otherwise they are likely to hit Ctrl-C and kill the whole thing.
If you'd like the main to return but be able to keep the background threads running, it's a tad bit more complicated, but it uses both of the solutions I just mentioned:
create a pipe()
fork() (but no execve())
from within the forked app. (child) open Gtk window, background thread, etc.
when last Gtk window is closed, send message over pipe
parent process receives message and quits immediately
child process still attempts a "join()" to wait for the background thread
This way, the background process with threads created in (3) can continue to run (your function still needs to wait for all the threads to end with the "join()" call), however, the use has a sense of "the app. is done" since it returns to the next line on the prompt in your console even though a background process is still running.
The pipe() and wait on a message on the pipe() is not required if you don't mind having your application always running in the background.
Note: that usage of fork() is most often seen when creating processes that want to run in the background (i.e. services, often called servers under Unix). That's how they get their PPID set to 1.
On Windows, you need to create a Windows/Linux/Mac Service or run the process in background. On Linux you need to create a daemon service or run the process in the background. Services allow to automatically start the process on boot.