It would have helped if you used <code> ... </code> tags: #!/usr/bin/perl
# daemonize the program
print "Parent pid: $$\n"; # I added this
&daemonize;
$| = 1;
while(1) {
print "\nIn the While\n";
open(MYFILE,'>>temp.txt');
print MYFILE "Hello Sri\n";
close(MYFILE);
}
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: $!";
open STDERR, '>>/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: $!";
umask 0;
}
Works for me:/home/user1> ./gashd.pl
Parent pid: 7300
/home/user1> ps
PID TTY TIME CMD
7190 pts/2 00:00:00 bash
7301 pts/2 00:00:02 gashd.pl
7315 pts/2 00:00:00 ps
Do you have any error messages?
Update: I was wrong, it is not working. My mistake was in copying your code, which does not have:use warnings;
use strict;
which points out that setsid is a bare-word. What you need is POSIX::setsid In fact the ps output should have shown me that it was not creating a new session. Here is a version, which also logs the error when trying to open the file.#!/usr/bin/perl
# daemonize the program
use warnings;
use strict;
use POSIX ('setsid');
use Sys::Syslog qw(:standard);
print "Parent pid: $$\n"; # I added this
&daemonize;
$| = 1;
while(1) {
print "\nIn the While\n";
if (!open(MYFILE,'>>temp.txt')) {
my $err = $!; # In case Sys::Syslog resets it
# Log pid with messages, set our facility to be LOCAL0
openlog($0, 'pid', 'LOG_LOCAL0');
syslog('LOG_ERR', "Unable to open temp.txt: $err");
closelog();
}
print MYFILE "Hello Sri\n";
close(MYFILE);
}
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: $!";
open STDERR, '>>/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: $!";
POSIX::setsid();
umask 0;
}
Check /var/log/messages (by default) for syslog messages, under an ordinary user I get:Feb 11 11:08:44 yogi ./gashd.pl[10467]: Unable to open temp.txt: Permi
+ssion denied
|