In C, is it possible to have the forked() process alive indefinitely even after the parent exits?
The idea of what I am trying to do is, Parent process forks a child, then exits, child keeps running in background until another process sends it a kill signal.
Yes, it is definitely possible to keep the child alive. The other responders are also correct; this is how a "daemon" or background process runs in a Linux environment.
Some call this the "fork off and die" approach. Here's a link describing how to do it:
http://wiki.linuxquestions.org/wiki/Fork_off_and_die
Note that more than just fork()-ing is done. File descriptors are closed to keep the background process from tying up system resources, etc.
Kerrek is right, this exactly the way how every daemon is implemented. So, your idea is perfect.
There is a daemon library function which is very easy to use for that.
The daemon() function call is not without limitations if you want to
write a well-behaved daemon. See On Starting Daemons
for an explanation.
Briefly: A good daemon should only background when it is ready to field requests, but do its setup under its own PID and print startup errors
Related
This may seem to be a dumb question but I don't really have a good understanding of fork() other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed via fork(), how to correctly assign tasks to parent process and child process?
Check the return value of fork. The child process will receive the value of 0. The parent will receive the value of the process id of the child.
Read Advanced Linux Programming which has an entire chapter dedicated to processes (because fork is difficult to explain);
then read documentation of fork(2); fork is not about multi-threading, but about creating processes. Threads are generally created with pthread_create(3) (which is implemented above clone(2), a Linux specific syscall). Read some pthreads tutorial to learn more about threads.
PS. fork is difficult to understand (you'll need hours of reading, some experimentation, perhaps using strace(1), till you reach the "AhAh" insight moment when you have understood it) since it returns twice on success. You need to keep its result, and you need to test the result for the three cases : <0 (failure), ==0 (child), >0 (parent). Don't forget to later call waitpid(2) (or something similar) in the parent, to avoid having zombie processes.
I am looking for C code to use on a Linux based system to start another process asynchronously. The second process should continue, even if the first ends. I've looked through the "fork" and "system" and "exec" options, but don't see anything that will spawn a peer process that's not communicating with or a child of the original process.
Can this be done?
Certainly you can. In the parent fork() a child, and in that child first call daemon() (which is an easy way to avoid setsid etc.), then call something from the exec family.
In Linux (and Unix), every process is created by an existing process. You may be able to create a process using fork and then, kill the parent process. This way, the child will be an orphan but still, it gets adopted by init. If you want to create a process that is not inherited by another, I am afraid that may not be possible.
You do a fork (man 2 fork) followed by an execl (man 2 execl)
For creates a new process of the same image as the calling process (so a perfect twin), where execl replaces one of the twins with a new image.
If you search google for "fork execl" you will find many text book examples -- including how to use correctly fork() and exec()
The most common fork-execl you will still have the new process associated to the terminal -- to create a perfect background process you need to create what is called a daemon process -- the template for that can be fornd in this answer here Creating a daemon in Linux
Not long ago, I wondered about the question: why are all processes killed when you close a terminal on Linux, and not passed to the "init" process (with pid 1)?
Because, all child processes are adopted by "init" process after termination of the parent.
Please, help me understand difference and the errors in my reasoning.
And also:
If it's possible, then can we use a system call to stop this happening? I think, that for this the programs need use setsid(), but in practice it's not correct.
As explained by cnicutar, it's due to the SIGHUP sent to all processes in the process group associated with the controlling terminal. You may either install a handler for this signal or ignore it completely. For arbitrary programs, you can start them with the nohup utility designed for this purpose.
You can also place the process in a new process group without a controlling terminal.
why on close terminal on linux all his processes will terminated, but
not passed to "init" process (with pid 1)
The processes are losing their controlling terminal so the kernel sends them a SIGHUP. The default action of SIGHUP is to terminate the process.
i think this will help you to understand
http://www.digipedia.pl/usenet/thread/18802/10189/
I am creating a GTK application in C. I am creating a child process using fork and then replacing it with execve("crawler",arg,env); which crawls my home directory and stores all the filenames in a file.
Now, this child process takes some time (about 2-5 minutes).
In the mean time, when this child process is running, the main GTK parent program is waiting.
But when the child process is running, after some time, the GTK application hangs.
I have tried gdk_thread_enter()/leave() in my main function.
But still I am the application is hanging.
Please, point out a mistake if any or else suggest any modification.
execve does not create a child process, it replaces the current process with the child. Are you sure you used fork() first, and then execve() from within the child?
EDIT since you're already using fork/execve, perhaps the child process is still interacting with Gtk somehow. Best to use Glib/Gtk+-specific functions for invoking the crawler -- try, for instance, g_spawn_command_line_async
If what you mean by "when this child process is running, the main GTK parent program is waiting" is that your code executes a wait(), waitid(), waitpid() in its main thread, then the app will indeed suspend execution until a child terminates (unless you've selected NOHANG option).
If your Gtk app doesn't need to coordinate further with your crawler program, just use the previously-mentioned
g_spawn_command_line_async routine, and do not set G_SPAWN_DO_NOT_REAP_CHILD. If you do need to coordinate, you could set that flag, and create a GChildWatch source, or perhaps could use one of the g_spawn pipe routines.
As I interpret gdk_thread_enter()/leave(), they are locking or unlocking threading, rather than running or stopping new threads. Gtk callbacks run in the main thread, so as indicated above, a blocking waitpid() in a callback will hang the Gtk app. A non-blocking waitpid() in a timer callback (eg) is not a problem, however.
Current scenario, I launch a process that forks, and after a while it aborts().
The thing is that both the fork and the original process print to the shell, but after the original one dies, the shell "returns" to the prompt.
I'd like to avoid the shell returning to the prompt and keep as if the process didn't die, having the child handle the situation there.
I'm trying to figure out how to do it but nothing yet, my first guess goes somewhere around tty handling, but not sure how that works.
I forgot to mention, the shell takeover for the child could be done on fork-time, if that makes it easier, via fd replication or some redirection.
I think you'll probably have to go with a third process that handles user interaction, communicating with the "parent" and "child" through pipes.
You can even make it a fairly lightweight wrapper, just passing data back and forth to the parent and terminal until the parent dies, and then switching to passing to/from the child.
To add a little further, as well, I think the fundamental problem you're going to run into is that the execution of a command by the shell just doesn't work that way. The shell is doing the equivalent of calling system() -- it's going to wait for the process it just spawned to die, and once it does, it's going to present the user with a prompt again. It's not really a tty issue, it's how the shell works.
bash (and I believe other shells) have the wait command:
wait: wait [n]
Wait for the specified process and report its termination status. If
N is not given, all currently active child processes are waited for,
and the return code is zero. N may be a process ID or a job
specification; if a job spec is given, all processes in the job's
pipeline are waited for.
Have you considered inverting the parent child relationship?
If the order in which the new processes will die is predictable, run the code that will abort in the "child" and the code that will continue in the parent.