Hi
i want to create a programm that "forks" itself into the background. If i use fork and exit the main process the child process are all terminated. So has anybody help?
Printable View
Hi
i want to create a programm that "forks" itself into the background. If i use fork and exit the main process the child process are all terminated. So has anybody help?
>So has anybody help?
It's pretty simple, really:
Code:if ((child = fork()) == -1) {
perror("Forked failed");
return 1;
}
if (child == 0) {
if (setsid() == -1)
perror("Set to session leader failed");
else {
/* Do what daemons do, hide and toil */
}
return 1; /* Never returns */
}
return 0; /* Parent goes *poof!* */
I remember we had to make a simple shell last year, and one of the features of the shell was do have a command where you could create a daemon on a terminal. For example, daemon ./program would make ./program a daemon process. Our professor told us that we should fork() twice and then kill the grand parent. I never really figured out how that worked. Can some tell me how that would work?
Forking twice helps to prevent the daemon from having an acquiring terminal. This can only happen under rules, and therefore isn't always necessary.
Check "Advanced Programming in the
UNIX Environment" by W. Richard Stevens", or google, where you're sure to find more information.
So the solution that twm gave still has a terminal attached to a process?
This is what google gave me, it has a quote from Steven's book. I don't have that book to hand, so I can't guarantee it's accurate.Quote:
Originally posted by Yasir_Malik
So the solution that twm gave still has a terminal attached to a process?
http://dbforums.com/archives/t316468.html
Hi,
I experienced some problems while porting some programs from Solaris to Linux. They are all calling fork() after being started so they run in daemon mode. I also have a debug mode that just skip the daemonize function that I wrote. (this function actually just call the fork method and make the parent process to exit normally and the child process to continu the execution of the program).
My problem is that while it run in daemon mode, it exit after a while without any warning/error/log message/etc... so I really don't know what is happening. I tested for days in debug mode and it works just fine and could run for months without problem.
So, I guess that it's all coming from the dameonize function that is actually calling fork(). I have few question that may answer and solve my problem:
1- Normally on Solaris, fork() duplicate the overall memory space of a process, is it the same under Linux or should I make alll my dynamic memory allocation after the fork() call?
2-What is the difference with the other fork() function: vfork, and so on... ? Is one of them more appropriate for what I'm doing?
3-Any other thought/suggestions about this?
Thank you very much!
Twisgabak.