code_junkie

How do I fork properly with mod_perl2

Nov 13th, 2011
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. use POSIX; # required for setsid
  2.  
  3. # Do not wait for child processes to complete
  4. $SIG{CHLD} = 'IGNORE';
  5.  
  6. # fork (and make sure we did!)
  7. defined (my $kid = fork) or die "Cannot fork: $!n";
  8.  
  9. if ($kid) {
  10. return (1, $kid);
  11. }else {
  12. # chdir to /, stops the process from preventing an unmount
  13. chdir '/' or die "Can't chdir to /: $!";
  14.  
  15. # dump our STDIN and STDOUT handles
  16. open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
  17. open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
  18.  
  19. # redirect for logging
  20. open STDERR, '>', $log_filename or die "Can't write to log: $!";
  21.  
  22. # Prevent locking to apache process
  23. setsid or die "Can't start a new session: $!";
  24.  
  25. # execute the command
  26. exec( $cmd, @args );
  27.  
  28. die "Failed to exec";
  29. }
  30.  
  31. close STDIN;
  32. close STDOUT;
  33. close STDERR;
  34. setsid();
  35.  
  36. $SIG{CHLD} = 'IGNORE';
  37.  
  38. # This should flush stdout.
  39. my $ofh = select(STDOUT);$| = 1;select $ofh;
  40.  
  41. my $kpid = fork;
  42. if ($kpid)
  43. {
  44. # Parent process
  45. waitpid($kpid, 0);
  46. }
  47. else
  48. {
  49. close STDIN;
  50. close STDOUT;
  51. close STDERR;
  52. setsid();
  53. my $gpid = fork;
  54. if (!$gpid)
  55. {
  56. open(STDIN, "</dev/null") ;#or print DEBUG2 "can't redirect stdinn";
  57. open(STDOUT, ">/dev/null") ;#or print DEBUG2 "can't redirect stdoutn";
  58. open(STDERR, ">/dev/null") ;#or print DEBUG2 "can't redirect stderrn";
  59. # Child process
  60. exec($pgm, @execargs) ;# or print DEBUG2 "exec failedn";
  61. }
  62. exit 0;
  63. }
Add Comment
Please, Sign In to add comment