• Publicidad

Correr script de Perl como daemon

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Correr script de Perl como daemon

Notapor jcovenas » 2012-03-29 16:47 @741

Uso Ubuntu 10.04. Tengo el siguiente script Perl y deseo que funcione como un daemon:
Leí sobre crear un script bash que llame a mi script Perl y luego ponerlo en el rc.local,
nada de esto me ha funcionado, seguí está guía, pero nada. Muchas Gracias.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl -w
  2. use warnings;
  3. use strict;
  4. use Net::POP3;
  5.  
  6.  my $ServerName = "mi server mail";
  7.  my $UserName = "mi user ";
  8.   my $Password = "cfsRSgfg!";
  9. # The program will run in an infinite loop.
  10. # while('TRUE')                
  11. # {
  12.         print "Waiting for email...\n";
  13.  
  14. # Connect to pop3 server
  15. my $pop3 = Net::POP3->new($ServerName) || die "Error : Couldn't log on to server";
  16.  
  17. # Login to pop3 server
  18. my $Num_Message = $pop3->login($UserName,$Password);
  19. my $Messages = $pop3->list();
  20.  
  21. my ($MsgId, $MsgDate, $MsgFrom, $MsgTo, $MsgCc, $MsgSub);
  22. my ($MsgAttach, $MsgSize, $MsgHeader, $MsgHeadFlg, $MsgBody,$MsgNo);
  23.  
  24.  
  25. foreach $MsgNo (keys %$Messages)
  26. {
  27.   my $MsgContent = $pop3->get($MsgNo);
  28.   my $count = 0;
  29.   $MsgHeadFlg = 0;
  30.   $MsgBody = "";
  31. # print "Message No : $MsgNo\n";
  32.   $MsgSize = $pop3->list($MsgNo);
  33. # print "Message Size : $MsgSize Bytes\n";
  34.  
  35.  # Process message data
  36.   while()
  37.   {
  38.  
  39.     # Exit if last line of mail
  40.     if ($count >= scalar(@$MsgContent))
  41.     {
  42.         $MsgBody =~s/^\s*(.*?)\s*$/$1/;
  43.         $MsgBody = "SMS de-$MsgFrom:" . $MsgBody;
  44. #       print "$MsgBody";
  45.         # You can only send SMS in chunks of 160 chars Max according to gnokii.
  46.         # so breaking the body into chunks of 160 and sending them 1 at a time.
  47.          if ($MsgSub =~ /^[+]?\d+$/ )
  48.                 {
  49.                 my @stringChunksArray = ($MsgBody =~ m/(.{1,160})/gs);
  50.                 for(my $i=0;$i<@stringChunksArray;$i++)
  51.                         {
  52.                         open(GNOKII, "| gammu --sendsms TEXT $MsgSub") || die "Error starting gnokii failed: $!\n";    
  53.                         # Start gnokii and wait for the SMS body
  54.                         print GNOKII $stringChunksArray[$i];                                                           
  55.                         # Print the SMS body in 160 Char chunks
  56.                         close(GNOKII);
  57.                         sleep(10);               # This is there so that the phone gets time to reset after each message. Otherwise the send fails
  58.                         }
  59.                 }
  60.         else
  61.                 {
  62.                 print "no es un Cel";
  63.                 last;
  64.                 }
  65.       last;
  66.     }
  67.  
  68.     # Check if end of mail header
  69.     if (@$MsgContent[$count] =~ /^\n/)
  70.     {
  71.       $MsgHeadFlg = 1;
  72.     }
  73.  
  74.     # Proceed if message header not processed
  75.     if (not $MsgHeadFlg)
  76.     {
  77.  
  78.       # Split the line
  79.       my @LineContent = split /: /, @$MsgContent[$count];
  80.  
  81.       # Check Header Info
  82.               SWITCH:
  83.               {
  84.                 # Get message date
  85.                 $LineContent[0] =~ /Date/i && do
  86.                                                {
  87.                                                  $MsgDate = $LineContent[1]; # print "Date : $MsgDate";
  88.                                                 last SWITCH;
  89.                                                };
  90.                 # Get message id
  91.                 $LineContent[0] =~ /Message-ID/i && do
  92.                                                {
  93.                                                  $MsgId = $LineContent[1]; # print "Message ID : $MsgId";
  94.                                                 last SWITCH;
  95.                                                };
  96.                 # Get message from
  97.                 $LineContent[0] =~ /From/i && do
  98.                                               {
  99.                                                 $MsgFrom = $LineContent[1];
  100.                                                 # $MsgFrom = $1;
  101.                                                 $MsgFrom =~ s/"|<.*>//g;
  102.                                                 $MsgFrom = substr($MsgFrom, 0, 39);
  103.                                                 # print "From : $MsgFrom";
  104.                                                 last SWITCH;
  105.                                               };
  106.                 # Get message to
  107.                 $LineContent[0] =~ /To/i && do
  108.                                               {
  109.                                                 $MsgTo = $LineContent[1]; #print "To : $MsgTo";
  110.                                                 last SWITCH;
  111.                                               };
  112.                 # Get message cc
  113.                 $LineContent[0] =~ /Cc/i && do
  114.                                               {
  115.                                                 $MsgCc = $LineContent[1]; # print "Cc : $MsgCc";
  116.                                                 last SWITCH;
  117.                                               };
  118.                 # Get message subject
  119.                 $LineContent[0] =~ /Subject/i && do
  120.                                               {
  121.                                                 $MsgSub = $LineContent[1];# print "Subject : $MsgSub";
  122.                                                 last SWITCH;
  123.                                               };
  124.               }
  125.     }
  126.     else
  127.     {
  128.       # Process message body
  129.       $MsgBody .= @$MsgContent[$count];
  130.     }
  131.     $count++;
  132.   } #end while
  133.  
  134. $pop3->delete ($MsgNo); # después de procesarlo: eliminarlo
  135.  
  136. } #end foreach
  137.  
  138. # Disconnect from pop3 server
  139. $pop3->quit();
  140. sleep(20);                              # Sleep for 20 seconds
  141.  
  142. #} # end while infinito
  143.  
  144.  
Coloreado en 0.007 segundos, usando GeSHi 1.0.8.4

¿Me dan una mano?
jcovenas
Perlero nuevo
Perlero nuevo
 
Mensajes: 13
Registrado: 2012-03-29 11:21 @514

Publicidad

Re: Correr script de Perl como daemon

Notapor explorer » 2012-03-29 17:35 @774

Bienvenido a los foros de Perl en Español, jcovenas.

Para hacer un dæmon, hay que cumplir una serie de reglas y hacer una serie de pasos.

Por ejemplo, la línea 62 es un print normal:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.                 print "no es un Cel";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Esto es algo que un dæmon no debe hacer, porque se supone que su salida estándar va a estar cerrada. Lo que sí puede hacer es dirigir esa salida a algún fichero de log o al sistema syslog.

Los pasos que hay que realizar son:
  • cambiar el directorio de trabajo a "/"
  • hacer un fork(), y que el proceso padre muera
  • desconectarte de la terminal cerrando las entradas y salidas estándares
  • disociarse de la terminal y dejar de formar parte del grupo de procesos que inició tu proceso padre
  • hacer otro fork() y dejar que muera el primer hijo. Esto es para impedir de todas maneras que la terminal sea controlada por nosotros. Continuaremos con el nieto
  • inicializar a 0 la máscara de creación de archivos
Bueno, dependiendo de la documentación que leas, algunos pasos pueden ir en otro orden, y no pasaría nada.

En Perl, se puede tener una subrutina que haga todo eso:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. sub daemonizar {
  2.    use POSIX;
  3.    POSIX::setsid or die "setsid: $!";                              # disociar de la terminal
  4.    my $pid = fork ();                                              # ¡fork!
  5.    if ($pid < 0) {                                                 # si ha fallado el fork...
  6.       die "fork: $!";                                              # nos morimos... algo raro pasó
  7.    } elsif ($pid) {                                                # pero, si somos el padre
  8.       exit 0;                                                      # nos morimos...
  9.    }                                                               # sigue el hijo
  10.    chdir "/";                                                      # cambio de directorio de trabajo
  11.    umask 0;                                                        # máscara de creación de archivos a 0
  12.    foreach (0 .. (POSIX::sysconf (&POSIX::_SC_OPEN_MAX) || 1024))  # cerramos todos los gestores
  13.       { POSIX::close $_ }                                          # que pudieran estar abiertos
  14.    open (STDIN,  "</dev/null");                                    # cerramos la entrada estándar
  15.    open (STDOUT, ">/dev/null");                                    # y la salida estándar
  16.    open (STDERR, ">&STDOUT"  );                                    # y la salida estándar de errores
  17.  }
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Después de llamar a esta subrutina, tu programa ya es un dæmon, así que debe entrar en un bucle infinito, haciendo lo que suelen hacer los dæmon...

Hay otra forma, más cómoda y moderna de hacer esto. Con la ayuda del módulo Proc::Daemon, que realiza estos pasos más el de generar un segundo hijo, por seguridad.

Un programa típico sería:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5. use Proc::Daemon;
  6.  
  7. Proc::Daemon::Init;                     # nos convertimos en dæmon
  8.  
  9. my $continue = 1;                       # esta bandera indica si el proceso debe seguir o no
  10. $SIG{TERM} = sub { $continue = 0 };     # capturamos la señal de interrupción
  11.                                         # cuando el usuario o sistema nos mande esta señal,
  12.                                         # se cambia la bandera, y el proceso termina
  13.  
  14. while ($continue) {                     # mientras podamos continuar...
  15.      ....;                              # aquí estará nuestro programa
  16. }
  17.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Aquí tienes descrito lo que tienes que hacer si quieres integrar tu dæmon en un sistema /etc/init.d.

Aquí tienes otro ejemplo por si, además, quieres controlar que solo exista una copia de tu dæmon en el sistema, con la ayuda de Proc::PID::File:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Proc::Daemon;
  7. use Proc::PID::File;
  8.  
  9. MAIN:
  10. {
  11.     # Demoniza
  12.     Proc::Daemon::Init();
  13.  
  14.     # Si ya estábamos corriendo, salimos
  15.     if (Proc::PID::File->running()) {
  16.         exit(0);
  17.     }
  18.  
  19.     # Inicialización
  20.     ...;
  21.  
  22.     # Bucle infinito
  23.     for (;;) {
  24.         ...;
  25.     }
  26. }
  27.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

En el bucle infinito, debes poner algún sistema de espera, para impedir que el proceso se ejecute sin parar, a toda velocidad, pues podría agotar la CPU. Puede ser un sleep() para que se ejecute cada cierto tiempo, o usar select() para que haga eso mismo además de indicar la llegada de alguna petición externa (vía sockets, por ejemplo). O un accept() si estás esperando una conexión externa.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Correr script de Perl como daemon

Notapor jcovenas » 2012-03-30 08:42 @404

Un millón de gracias, explorer. Entendí el tema de hacerlo independiente y eliminar los print() de la terminal, no sabía sobre el módulo Proc::Daemon. Aun así usé un modelo de skeleton.
El código es el siguiente:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl -w
  2. #
  3. # mydaemon.pl by Andrew Ault, http://www.andrewault.net
  4. #
  5. # Free software. Use this as you wish.
  6. #
  7. # Throughout this template "mydaemon" is used where the name of your daemon should
  8. # be, replace occurrences of "mydaemon" with the name of your daemon.
  9. #
  10. # This name will also be the exact name to give this file (WITHOUT a ".pl" extension).
  11. #
  12. # It is also the exact name to give the start-stop script that will go into the
  13. # /etc/init.d/ directory.
  14. #
  15. # It is also the name of the log file in the /var/log/ directory WITH a ".log"
  16. # file extension.
  17. #
  18. # Replace "# do something" with your super useful code.
  19. #
  20. # Use "# logEntry("log something");" to log whatever your need to see in the log.
  21. #
  22. use strict;
  23. use warnings;
  24. use POSIX;
  25. use File::Pid;
  26. use Net::POP3;
  27.  
  28. # make "mydaemon.log" file in /var/log/ with "chown root:adm mydaemon"
  29.  
  30. # TODO: change "mydaemon" to the exact name of your daemon.
  31. my $daemonName    = "mail2sms";
  32. my $dieNow        = 0;                                     # used for "infinte loop" construct - allows daemon mode to gracefully exit
  33. my $sleepMainLoop = 120;                                    # number of seconds to wait between "do something" execution after queue is clear
  34. my $logging       = 1;                                     # 1= logging is on
  35. my $logFilePath   = "/var/log/";                           # log file path
  36. my $logFile       = $logFilePath . $daemonName . ".log";
  37. my $pidFilePath   = "/var/run/";                           # PID file path
  38. my $pidFile       = $pidFilePath . $daemonName . ".pid";
  39.  
  40. # daemonize
  41. use POSIX qw(setsid);
  42. chdir '/';
  43. umask 0;
  44. open STDIN,  '/dev/null'   or die "Can't read /dev/null: $!";
  45. open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
  46. open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
  47. defined( my $pid = fork ) or die "Can't fork: $!";
  48. exit if $pid;
  49.  
  50. # dissociate this process from the controlling terminal that started it and stop being part
  51. # of whatever process group this process was a part of.
  52. POSIX::setsid() or die "Can't start a new session.";
  53.  
  54. # callback signal handler for signals.
  55. $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signalHandler;
  56. $SIG{PIPE} = 'ignore';
  57.  
  58. # create pid file in /var/run/
  59. my $pidfile = File::Pid->new( { file => $pidFile, } );
  60.  
  61. $pidfile->write or die "Can't write PID file, /dev/null: $!";
  62.  
  63. # turn on logging
  64. if ($logging) {
  65.         open LOG, ">>$logFile";
  66.         select((select(LOG), $|=1)[0]); # make the log file "hot" - turn off buffering
  67. }
  68.  
  69. # "infinite" loop where some useful process happens
  70. until ($dieNow) {
  71.         sleep($sleepMainLoop);
  72.  
  73.         # TODO: put your custom code here!
  74.         # do something
  75. ######################################
  76.  my $ServerName = "mi server mail";
  77.  my $UserName = "mi user";
  78.  my $Password = "algo";
  79. # The program will run in an infinite loop.
  80. # while('TRUE')                
  81.  #{
  82.         #print "Waiting for email...\n";       
  83.  
  84. # Connect to pop3 server
  85. my $pop3 = Net::POP3->new($ServerName) || die "Error : Couldn't log on to server";
  86.  
  87. # Login to pop3 server
  88. my $Num_Message = $pop3->login($UserName,$Password);
  89. my $Messages = $pop3->list();
  90.  
  91. my ($MsgId, $MsgDate, $MsgFrom, $MsgTo, $MsgCc, $MsgSub);
  92. my ($MsgAttach, $MsgSize, $MsgHeader, $MsgHeadFlg, $MsgBody,$MsgNo);
  93.  
  94.  
  95. foreach $MsgNo (keys %$Messages)
  96. {
  97.   my $MsgContent = $pop3->get($MsgNo);
  98.   my $count = 0;
  99.   $MsgHeadFlg = 0;
  100.   $MsgBody = "";
  101.  # print "Message No : $MsgNo\n";
  102.  
  103.   $MsgSize = $pop3->list($MsgNo);
  104. #  print "Message Size : $MsgSize Bytes\n";
  105.  
  106.   # Process message data
  107.   while()
  108.   {
  109. #       print scalar(@$MsgContent);
  110. #       print "es el scalar\n";
  111. #       print $count;
  112. #       print "es el count...\n";      
  113.     # Exit if last line of mail
  114.     if ($count >= scalar(@$MsgContent))
  115.     {
  116.         $MsgBody =~s/^\s*(.*?)\s*$/$1/;
  117.         $MsgBody = "SMS de-$MsgFrom:" . $MsgBody;
  118.         #print "$MsgBody";
  119.         # You can only send SMS in chunks of 160 chars Max according to gnokii.
  120.         # so breaking the body into chunks of 160 and sending them 1 at a time.
  121.          if ($MsgSub =~ /^[+]?\d+$/ )
  122.                 {
  123.                 my @stringChunksArray = ($MsgBody =~ m/(.{1,160})/gs);
  124.                 for(my $i=0;$i<@stringChunksArray;$i++)
  125.                         {
  126.                         open(GNOKII, "| gammu --sendsms TEXT $MsgSub") || die "Error starting gnokii failed: $!\n";    
  127.                         # Start gnokii and wait for the SMS body
  128.                         print GNOKII $stringChunksArray[$i];                                                           
  129.                         # Print the SMS body in 160 Char chunks
  130.                         close(GNOKII);
  131.                         sleep(10);               # This is there so that the phone gets time to reset after each message. Otherwise the send fails
  132.                         }
  133.                 }
  134.         else
  135.                 {
  136.                 #print "no es un Cel";
  137.                 last;
  138.                 }
  139.       last;
  140.     }
  141.  
  142.     # Check if end of mail header
  143.     if (@$MsgContent[$count] =~ /^\n/)
  144.     {
  145.       $MsgHeadFlg = 1;
  146.     }
  147.  
  148.     # Proceed if message header not processed
  149.     if (not $MsgHeadFlg)
  150.     {
  151.  
  152.       # Split the line
  153.       my @LineContent = split /: /, @$MsgContent[$count];
  154.  
  155.       # Check Header Info
  156.               SWITCH:
  157.               {
  158.                 # Get message date
  159.                 $LineContent[0] =~ /Date/i && do
  160.                                                {
  161.                                                  $MsgDate = $LineContent[1]; # print "Date : $MsgDate";
  162.                                                 last SWITCH;
  163.                                                };
  164.                 # Get message id
  165.                 $LineContent[0] =~ /Message-ID/i && do
  166.                                                {
  167.                                                  $MsgId = $LineContent[1]; print "Message ID : $MsgId";
  168.                                                 last SWITCH;
  169.                                                };
  170.                 # Get message from
  171.                 $LineContent[0] =~ /From/i && do
  172.                                               {
  173.                                                 $MsgFrom = $LineContent[1];
  174. #                                               $MsgFrom = $1;
  175.                                                 $MsgFrom =~ s/"|<.*>//g;
  176.                                                 $MsgFrom = substr($MsgFrom, 0, 39);            
  177.                                                 # print "From : $MsgFrom";
  178.                                                 last SWITCH;
  179.                                               };
  180.                 # Get message to
  181.                 $LineContent[0] =~ /To/i && do
  182.                                               {
  183.                                                 $MsgTo = $LineContent[1]; #print "To : $MsgTo";
  184.                                                 last SWITCH;
  185.                                               };
  186.                 # Get message cc
  187.                 $LineContent[0] =~ /Cc/i && do
  188.                                               {
  189.                                                 $MsgCc = $LineContent[1]; #print "Cc : $MsgCc";
  190.                                                 last SWITCH;
  191.                                               };
  192.                 # Get message subject
  193.                 $LineContent[0] =~ /Subject/i && do
  194.                                               {
  195.                                                 $MsgSub = $LineContent[1]; #print "Subject : $MsgSub";
  196.                                                 last SWITCH;
  197.                                               };
  198.               }
  199.     }
  200.     else
  201.     {
  202.       # Process message body
  203.       $MsgBody .= @$MsgContent[$count];
  204.     }
  205.     $count++;
  206.   } #end while
  207.  
  208. $pop3->delete ($MsgNo); # despues de procesarlo: eliminarlo
  209.  
  210. } #end foreach
  211.  
  212. # Disconnect from pop3 server
  213. $pop3->quit();
  214. sleep(20);                              # Sleep for 20 seconds
  215.  
  216. ##} # end while infinito
  217.  
  218.         ####print "wait.... \n";
  219.  
  220.         #logEntry("log something"); # use this to log whatever you need to
  221. }
  222.  
  223. # add a line to the log file
  224. sub logEntry {
  225.         my ($logText) = @_;
  226.         my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
  227.         my $dateTime = sprintf "%4d-%02d-%02d %02d:%02d:%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec;
  228.         if ($logging) {
  229.                 print LOG "$dateTime $logText\n";
  230.         }
  231. }
  232.  
  233. # catch signals and end the program if one is caught.
  234. sub signalHandler {
  235.         $dieNow = 1;    # this will cause the "infinite loop" to exit
  236. }
  237.  
  238. # do this stuff when exit() is called.
  239. END {
  240.         if ($logging) { close LOG }
  241.         $pidfile->remove if defined $pidfile;
  242. }
  243.  
  244.  
Coloreado en 0.008 segundos, usando GeSHi 1.0.8.4

¿Me recomendaría usar éste o implementar el que indicas?
jcovenas
Perlero nuevo
Perlero nuevo
 
Mensajes: 13
Registrado: 2012-03-29 11:21 @514

Re: Correr script de Perl como daemon

Notapor explorer » 2012-03-30 10:18 @471

La diferencia sería de 20 o 25 líneas menos.

El resultado será el mismo.

Bueno, no... será más seguro.

Siempre puedes consultar el código de Proc::Daemon para ver cómo lo hace ;)
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Correr script de Perl como daemon

Notapor jcovenas » 2012-03-30 11:53 @536

muchas gracias, veo que está funcionando. pero no tengo algo claro.
Cuando lo abro desde la terminal: sudo /usr/bin/mail2sms
empieza a trabajar pero no como un servicio. Hago esto para ejecutarlo: sudo /etc/init.d/mail2sms
y claro allí tengo un script que lo llama es un sh sin extensión.

Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. #! /bin/sh
  2. ### BEGIN INIT INFO
  3. # Provides:          skeleton
  4. # Required-Start:    $remote_fs $syslog
  5. # Required-Stop:     $remote_fs $syslog
  6. # Default-Start:     2 3 4 5
  7. # Default-Stop:      0 1 6
  8. # Short-Description: Example initscript
  9. # Description:       This file should be used to construct scripts to be
  10. #                    placed in /etc/init.d.
  11. ### END INIT INFO
  12.  
  13. # Author: Foo Bar <[email protected]>
  14. #
  15. # Please remove the "Author" lines above and replace them
  16. # with your own name if you copy and modify this script.
  17.  
  18. # Do NOT "set -e"
  19.  
  20. # PATH should only include /usr/* if it runs after the mountnfs.sh script
  21. PATH=/sbin:/usr/sbin:/bin:/usr/bin
  22. DESC="mail to sms"
  23. NAME=mail2sms
  24. DAEMON=/usr/sbin/$NAME
  25. DAEMON_ARGS="--options args"
  26. PIDFILE=/var/run/$NAME.pid
  27. SCRIPTNAME=/etc/init.d/$NAME
  28.  
  29. # Exit if the package is not installed
  30. [ -x "$DAEMON" ] || exit 0
  31.  
  32. # Read configuration variable file if it is present
  33. [ -r /etc/default/$NAME ] && . /etc/default/$NAME
  34.  
  35. # Load the VERBOSE setting and other rcS variables
  36. . /lib/init/vars.sh
  37.  
  38. # Define LSB log_* functions.
  39. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
  40. . /lib/lsb/init-functions
  41.  
  42. #
  43. # Function that starts the daemon/service
  44. #
  45. do_start()
  46. {
  47.         # Return
  48.         #   0 if daemon has been started
  49.         #   1 if daemon was already running
  50.         #   2 if daemon could not be started
  51.         start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
  52.                 || return 1
  53.         start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
  54.                 $DAEMON_ARGS \
  55.                 || return 2
  56.         # Add code here, if necessary, that waits for the process to be ready
  57.         # to handle requests from services started subsequently which depend
  58.         # on this one.  As a last resort, sleep for some time.
  59. }
  60.  
  61. #
  62. # Function that stops the daemon/service
  63. #
  64. do_stop()
  65. {
  66.         # Return
  67.         #   0 if daemon has been stopped
  68.         #   1 if daemon was already stopped
  69.         #   2 if daemon could not be stopped
  70.         #   other if a failure occurred
  71.         start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
  72.         RETVAL="$?"
  73.         [ "$RETVAL" = 2 ] && return 2
  74.         # Wait for children to finish too if this is a daemon that forks
  75.         # and if the daemon is only ever run from this initscript.
  76.         # If the above conditions are not satisfied then add some other code
  77.         # that waits for the process to drop all resources that could be
  78.         # needed by services started subsequently.  A last resort is to
  79.         # sleep for some time.
  80.         start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
  81.         [ "$?" = 2 ] && return 2
  82.         # Many daemons don't delete their pidfiles when they exit.
  83.         rm -f $PIDFILE
  84.         return "$RETVAL"
  85. }
  86.  
  87. #
  88. # Function that sends a SIGHUP to the daemon/service
  89. #
  90. do_reload() {
  91.         #
  92.         # If the daemon can reload its configuration without
  93.         # restarting (for example, when it is sent a SIGHUP),
  94.         # then implement that here.
  95.         #
  96.         start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
  97.         return 0
  98. }
  99.  
  100. case "$1" in
  101.   start)
  102.         [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
  103.         do_start
  104.         case "$?" in
  105.                 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
  106.                 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
  107.         esac
  108.         ;;
  109.   stop)
  110.         [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
  111.         do_stop
  112.         case "$?" in
  113.                 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
  114.                 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
  115.         esac
  116.         ;;
  117.   status)
  118.        status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
  119.        ;;
  120.   #reload|force-reload)
  121.         #
  122.         # If do_reload() is not implemented then leave this commented out
  123.         # and leave 'force-reload' as an alias for 'restart'.
  124.         #
  125.         #log_daemon_msg "Reloading $DESC" "$NAME"
  126.         #do_reload
  127.         #log_end_msg $?
  128.         #;;
  129.   restart|force-reload)
  130.         #
  131.         # If the "reload" option is implemented then remove the
  132.         # 'force-reload' alias
  133.         #
  134.         log_daemon_msg "Restarting $DESC" "$NAME"
  135.         do_stop
  136.         case "$?" in
  137.           0|1)
  138.                 do_start
  139.                 case "$?" in
  140.                         0) log_end_msg 0 ;;
  141.                         1) log_end_msg 1 ;; # Old process is still running
  142.                         *) log_end_msg 1 ;; # Failed to start
  143.                 esac
  144.                 ;;
  145.           *)
  146.                 # Failed to stop
  147.                 log_end_msg 1
  148.                 ;;
  149.         esac
  150.         ;;
  151.   *)
  152.         #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
  153.         echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
  154.         exit 3
  155.         ;;
  156. esac
  157.  
  158. :
  159.  
Coloreado en 0.006 segundos, usando GeSHi 1.0.8.4

Supongo que este script hace que pueda hacer un start y stop y luego ese lo metí en rc.local:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. update-rc.d mail2sms defaults 99
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Hago un
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. sudo ls /var/run/
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

y no lo veo corriendo.
jcovenas
Perlero nuevo
Perlero nuevo
 
Mensajes: 13
Registrado: 2012-03-29 11:21 @514

Re: Correr script de Perl como daemon

Notapor explorer » 2012-03-30 12:04 @544

Ejecútalo como

bash -x /etc/init.d/mail2sms start

y así verás qué es lo que hace.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Correr script de Perl como daemon

Notapor jcovenas » 2012-03-30 12:08 @547

Sintáxis: [ Descargar ] [ Ocultar ]
  1. ubuntu@ubuntu:~$ bash -x /etc/init.d/mail2sms start 
  2. + PATH=/sbin:/usr/sbin:/bin:/usr/bin 
  3. + DESC='mail to sms' 
  4. + NAME=mail2sms 
  5. + DAEMON=/usr/sbin/mail2sms 
  6. + DAEMON_ARGS='--options args' 
  7. + PIDFILE=/var/run/mail2sms.pid 
  8. + SCRIPTNAME=/etc/init.d/mail2sms 
  9. + '[' -x /usr/sbin/mail2sms ']' 
  10. + exit 0 
  11. ubuntu@ubuntu:~$  


Salió eso y no sé qué es lo que significa.

Leyendo mejor me dice que la ruta es de /usr/sbin.
En el path le di solo usr/bin.

Bien, ya lo veo correr, ahora el tema es que no lo puedo hacer booteable.
jcovenas
Perlero nuevo
Perlero nuevo
 
Mensajes: 13
Registrado: 2012-03-29 11:21 @514

Re: Correr script de Perl como daemon

Notapor explorer » 2012-03-30 16:28 @727

¿Qué significa eso de que no es booteable?
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Correr script de Perl como daemon

Notapor jcovenas » 2012-03-31 08:03 @377

Disculpe, quise decir que al momento de cargar Ubuntu no levanta el servicio.
Uso este comando:
Sintáxis: [ Descargar ] [ Ocultar ]
  1. update-rc.d /etc/init.d/mail2sms defaults 99 
jcovenas
Perlero nuevo
Perlero nuevo
 
Mensajes: 13
Registrado: 2012-03-29 11:21 @514

Re: Correr script de Perl como daemon

Notapor explorer » 2012-03-31 09:10 @423

Es así:
Sintáxis: [ Descargar ] [ Ocultar ]
  1. update-rc.d mail2sms defaults 99  

Como resultado de esa línea, deberás ver que hay enlaces simbólicos en /etc/rcX.d/ (siendo X los valores 2, 3, 4 y 5 para el arranque del servicio; y 0, 1 6 para la parada) que apuntan a mail2sms dentro de init.d/
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Siguiente

Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 44 invitados

cron