Здравствуйте Tom, Вы писали:
Tom>Помогите примером написания сабж.
Если я правильно помню, то нужно просто отключить программу от терминала. Вызов setsid устанавливает новую сессию и возвращает её id. Как точно это делается я не помню, сам я делал, кажется, так
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if (pid == -1)
{
printf("'fork()' failed.\n");
return -1;
}
if (!pid) return 0;
pid = setsid();
if (pid == -1)
{
/* реакция на ошибку */return -1;
}
return 0;
}
Здравствуйте Tom, Вы писали:
Tom>Помогите примером написания сабж.
Ochen prosto eto delaetsya funk. `daemon`
int main (){
daemon(1,0); // esli nado smotri man daemon
while (need_exit){
do_our_work();
}
return 0;
}
eto vkratse. esli nado chut uluchshit' , neobxodimo dobavit' obrabotchiki signalov TERM i HUP
hotelos by chto by ty ob etom prochital samostoyatelno No esli nichego ne naidesh , pomozhem
Здравствуйте Kubyshev Andrey, Вы писали:
KA>Здравствуйте Tom, Вы писали:
Tom>>Помогите примером написания сабж.
KA>Ochen prosto eto delaetsya funk. `daemon`
KA>int main (){ KA>daemon(1,0); // esli nado smotri man daemon KA>while (need_exit){ KA>do_our_work(); KA>} KA>return 0; KA>}
KA> KA>eto vkratse. esli nado chut uluchshit' , neobxodimo dobavit' obrabotchiki signalov TERM i HUP KA>hotelos by chto by ty ob etom prochital samostoyatelno No esli nichego ne naidesh , pomozhem
Za functciu konechno spasobo, no na moem Solaris7 net takoy A vot pro obrabotku signalov esli mogno to daite primer
[skip]
Спасибо сегодня попробую. Не могли бы вы прояснить очень не понятный момент: В контексте какого процесса и потока вызываются сигналы (если потоков много и выполняются они на разных процессорах, то как там это работает ?)
Здравствуйте Tom, Вы писали:
Tom>[skip] Tom>Спасибо сегодня попробую. Не могли бы вы прояснить очень не понятный момент: В контексте какого процесса и потока вызываются сигналы (если потоков много и выполняются они на разных процессорах, то как там это работает ?)
Vse tvoi threads poluchat etot signal i ego obrabotayut esli on u nih ne zamaskirovan. Obychno ya delayu tam , pered sozdaniem pervoi thread ili pered deamon , ya maskiruyu signal TERM i HUP
sozdayu pervuyu thread (vmeste s tem sozdaetsya thread manager) i razmaskiruyu eti signaly v main thread, a potom perehozhu na ozhidanie globalnoi condition variable. v obrabotchie HUPa naprimer ya save nomer signala v global variable i signalyu etot condition var i vyhozhu iz obrabotchika.
void myHUPhandler (int s){
sig_reason = s ;
sig_cond.broadcast();
}
Main thread prosypaetsya , vidit chto proizoshel signal HUP, perechityvaet konfiguratsiyu i snova zasypaet na condition var ... , nu a esli TERM , to soobschaet threadam chto nado quit putem ustanovki flaga , zhdet poka vyidut i vyhodit ...
Здравствуйте Tom, Вы писали:
Tom>Помогите примером написания сабж.
Не помню откуда это но здесь все написано
1.7 How do I get my program to act like a daemon?
A daemon process is usually defined as a background process that does not
belong to a terminal session. Many system services are performed by daemons;
network services, printing etc.
Simply invoking a program in the background isn't really adequate for these
long-running programs; that does not correctly detach the process from the
terminal session that started it. Also, the conventional way of starting
daemons is simply to issue the command manually or from an rc script; the
daemon is expected to put itself into the background.
Here are the steps to become a daemon:
1. fork() so the parent can exit, this returns control to the command line or
shell invoking your program. This step is required so that the new process
is guaranteed not to be a process group leader. The next step, setsid(),
fails if you're a process group leader.
2. setsid() to become a process group and session group leader. Since a
controlling terminal is associated with a session, and this new session has
not yet acquired a controlling terminal our process now has no controlling
terminal, which is a Good Thing for daemons.
3. fork() again so the parent, (the session group leader), can exit. This means
that we, as a non-session group leader, can never regain a controlling
terminal.
4. chdir("/") to ensure that our process doesn't keep any directory in use.
Failure to do this could make it so that an administrator couldn't unmount a
filesystem, because it was our current directory. [Equivalently, we could
change to any directory containing files important to the daemon's
operation.]
5. umask(0) so that we have complete control over the permissions of anything
we write. We don't know what umask we may have inherited. [This step is
optional]
6. close() fds 0, 1, and 2. This releases the standard in, out, and error we
inherited from our parent process. We have no way of knowing where these fds
might have been redirected to. Note that many daemons use sysconf() to
determine the limit _SC_OPEN_MAX. _SC_OPEN_MAX tells you the maximun open
files/process. Then in a loop, the daemon can close all possible file
descriptors. You have to decide if you need to do this or not. If you think
that there might be file-descriptors open you should close them, since
there's a limit on number of concurrent file descriptors.
7. Establish new open descriptors for stdin, stdout and stderr. Even if you
don't plan to use them, it is still a good idea to have them open. The
precise handling of these is a matter of taste; if you have a logfile, for
example, you might wish to open it as stdout or stderr, and open `/dev/null'
as stdin; alternatively, you could open `/dev/console' as stderr and/or
stdout, and `/dev/null' as stdin, or any other combination that makes sense
for your particular daemon.
Almost none of this is necessary (or advisable) if your daemon is being started
by inetd. In that case, stdin, stdout and stderr are all set up for you to
refer to the network connection, and the fork()s and session manipulation
should not be done (to avoid confusing inetd). Only the chdir() and umask()
steps remain as useful.
Любая проблема дизайна может быть решена введением дополнительного абстрактного слоя, за исключением проблемы слишком большого количества дополнительных абстрактных слоев
Любая проблема дизайна может быть решена введением дополнительного абстрактного слоя, за исключением проблемы слишком большого количества дополнительных абстрактных слоев