macli has asked for the wisdom of the Perl Monks concerning the following question:

I have a simple script I want to daemonize, but it won't and still hanging in the terminal.

#!/usr/bin/perl -T use strict; use warnings; use POSIX 'setsid'; $ENV{'PATH'} = '/bin:/usr/bin:/usr/sbin'; delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'}; my $p0f; my $pid; open($p0f, "p0f -l 'tcp dst port 25' 2>&1 | ") or die "Can't fork: $!" +; daemonize(); while(<$p0f>) { print if /Linux/; } sub daemonize { chdir '/' or die "Can't chdir to /: $!"; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!"; defined(my $pid = fork) or die "Can't fork: $!"; exit if $pid; setsid or die "Can’t start a new session: $!"; open STDERR, '>&STDOUT' or die "Can't dup stdout: $!"; }

the script is not backgrounded and parent process id still showing in ps command

I suspect it might be open($p0f, "p0f -l 'tcp dst port 25' 2>&1 | ") or die "Can't fork: $!" STDERR redirecting thing, anybody know how to detach STDIN/STDOUT/STDERR properly while I can still do the redirecting thing.

If I remove the daemonize sub and run the script as sample.pl & at terminal, it will be backgrounded properly. I would like daemonize sub to do the same thing as '&'.

Replies are listed 'Best First'.
Re: Can't daemonize because STDIN/STDOUT not detatched?
by Joost (Canon) on May 02, 2007 at 20:17 UTC
      Good catch, It backgrounded. what is the secret behind? I also would like to see print result from terminal
      while(<$p0f>) { print if /Linux/; }
      which standard handle I should keep open for child, STDERR or STDOUT? and How?
        I don't know what you're trying to do here. Daemonizing implies you don't have, want and use STDOUT STDIN and STDERR.

        So, either use STDOUT or don't daemonize. If you only want to run the process in the background while still polluting your STDOUT for some strange reason, just fork(), or (probably better) start the process in the background from the shell.