Perl学习之创建Linux进程


示例1:创建进程 

  1. #!/usr/bin/perl   
  2. #a simple demon   
  3. use strict;  
  4.   
  5. my $pid = fork();  
  6. print $pid."\n";  
  7. if($pid)  
  8. {  
  9.         print "processing...\n";  
  10.         exit(0);  
  11. }  
  12. else  
  13. {  
  14.         print "child processing...\n";  
  15. }  
  16. setpgrp();  
  17.   
  18. while(1)  
  19. {  
  20.         sleep(10);  
  21.         open(MYFILE,">>/tmp/test.log");  
  22.         my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);  
  23.         $year+=1900;$mon++;  
  24.   
  25.         print MYFILE ("Now is $year-$mon-$mday $hour:$min:$sec.\n");  
  26.         close(MYFILE);  
  27. }  

示例2:定时删除/tmp目录下的文件 

  1. #!/usr/bin/perl   
  2. use strict;  
  3.   
  4. our $DIR_PATH="/tmp";  
  5. &main();  
  6. exit;  
  7.   
  8. sub main  
  9. {     
  10.   
  11.     die( "Can't fork") unless defined (my $pid = fork());  
  12.     print "Process...\n$pid\n";  
  13.     setpgrp();  
  14.     while(1)  
  15.     {  
  16.         opendir DIR, ${DIR_PATH} or die "Can not open \"$DIR_PATH\"\n";  
  17.         my @filelist = readdir DIR;  
  18.         my @res;  
  19.         my $a;  
  20.         my $file;  
  21.   
  22.         open(MYFILE,">>/tmp/delfile.log");  
  23.   
  24.         foreach $file (@filelist)   
  25.         {  
  26.                 ($file eq ".."and next;  
  27.                 ($file eq  ".")  and next;  
  28.                 @res = stat($DIR_PATH."/".$file);  
  29.                 $a = time() - @res[10];  
  30.                   
  31.                 if ($a > 258200 )  
  32.                 {  
  33.                         system("rm -rf ".$DIR_PATH."/".$file);  
  34.                         print MYFILE $DIR_PATH."/".$file."\n";  
  35.                 }  
  36.         }  
  37.   
  38.         close(MYFILE);  
  39.         sleep(86400);  
  40.     }  
  41. }  

相关内容