Page 1 of 1

Create deamon thread? (SOLVED)

Posted: Sun Apr 01, 2007 8:55 pm
by SkyManager
Does anybody know how to create a deamon thread from PB :?:

Daemon code example for Purebasic (linux)

Posted: Mon May 07, 2007 11:44 am
by HarryE
Here is a way to create a daemon code in Purebasic for linux
Check glibc for details on used functions.

Tested on Arch linux.
Compile the example then open a console and run the compiled program (call it mydaemon for example)
With ps ax get the pid of the mydaemon, - check if it's running
then send signals to mydaemon using kill -HUP `pidof mydaemon`
or kill -PIPE `pidof mydaemon`
then kill -TERM `pidof mydaemon`
Check the result with cat log.txt
Modify the example to do something more useful...

Code: Select all

;Copyleft Harald Ersch 2007 
;Released under GNU GPL 2.0
;

Global bHup.l=0
Global bPipe.l=0
Global bTerm.l=0
Global SIGTERM=15
Global SIGKILL=9
Global SIGHUP=1
Global SIGPIPE=13
Global SIG_BLOCK=0
Procedure LogMe(t.s)
If OpenFile(0, "log.txt")        
          FileSeek(0, Lof(0))
          WriteStringN(0, t)  
     CloseFile(0)                       
  Else
 ;   MessageRequester("Information","Can't create the file!")
  EndIf
EndProcedure
; signal handler,- keep it short&fast
ProcedureC Dosig(sig.l)
Select sig
Case SIGHUP
bHup=1
Case SIGTERM
bTerm=1
Case SIGKILL
bTerm=1
Case SIGPIPE
bPipe=1
EndSelect
EndProcedure

*sset = AllocateMemory(1000) ; just a guess
sigfillset_(*sset)
sigdelset_(*sset,SIGHUP)
sigdelset_(*sset,SIGPIPE)
sigdelset_(*sset,SIGTERM)
sigdelset_(*sset,SIGKILL)    ; ignored anyway
sigprocmask_(SIG_BLOCK,*sset,0)
signal_(SIGHUP,@Dosig())
signal_(SIGPIPE,@Dosig())
signal_(SIGTERM,@Dosig())
signal_(SIGKILL,@Dosig())
; in parent process
pid.l=fork_()

Select pid;
Case 0
Case  -1
MessageRequester("Error","Coud not fork for some reason...")
End
Default
End
EndSelect

;Do whatever you like here, you are in the child now
; stdin, stdout and stderr should be closed or redirected in the child
; I don't know how to do it without breaking internals of PB.
; avoid using them in the child, use files or sockets instead

;Main loop, do your processing inside
While bTerm=0
Delay(100)     ;
If bPipe=1 
LogMe("PIPE SIGNAL RECEIVED")
bPipe=0
EndIf
If bHup=1 
LogMe("HUP SIGNAL RECEIVED") 
bHup=0
EndIf
If bTerm=1 
LogMe("TERM SIGNAL RECEIVED")
EndIf

Wend

Posted: Wed May 16, 2007 5:40 am
by SkyManager
Thanks a lot HarryE. :D
It works on my Red Hat 9