Run as a daemon or service: Difference between revisions

Content added Content deleted
(Added Wren)
m (syntax highlighting fixup automation)
Line 11: Line 11:
==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
{{trans|QB64}}
{{trans|QB64}}
<lang freebasic>ScreenLock()
<syntaxhighlight lang="freebasic">ScreenLock()
Open "c:\Users\Default\Documents\myDaemon.log" For Append As #1
Open "c:\Users\Default\Documents\myDaemon.log" For Append As #1
'Open "myDaemon.log" For Append As #1 'Ruta de archivo relativa para la salida // Relative file path for the output
'Open "myDaemon.log" For Append As #1 'Ruta de archivo relativa para la salida // Relative file path for the output
Line 22: Line 22:
Close #1 'Cierra el archivo previamente abierto para escritura // Close the file previously open for writing
Close #1 'Cierra el archivo previamente abierto para escritura // Close the file previously open for writing
ScreenUnlock()
ScreenUnlock()
End</lang>
End</syntaxhighlight>


==={{header|QB64}}===
==={{header|QB64}}===
<lang freebasic>'Metacommands and Statements for closing console or window
<syntaxhighlight lang="freebasic">'Metacommands and Statements for closing console or window
'' The following line is double commented ('') as some metacommands still execute even when singularly commented (')
'' The following line is double commented ('') as some metacommands still execute even when singularly commented (')
''$Console 'Closes the console but does not close the main window, used for whole program run
''$Console 'Closes the console but does not close the main window, used for whole program run
Line 40: Line 40:
Next i%
Next i%
Close #1 'Closes the file previously opened for writing
Close #1 'Closes the file previously opened for writing
System</lang>
System</syntaxhighlight>
{{out}}
{{out}}
<pre>09:02:23 - Running
<pre>09:02:23 - Running
Line 54: Line 54:
The task also wants to redirect stdout. This program does so with [http://netbsd.gw.com/cgi-bin/man-cgi?dup2+2+NetBSD-current dup2(2)]. Had we wanted to directly write to a file, we could open the file with <code>file = fopen(argv[1], "a")</code>, and write to ''file'' instead of ''stdout''.
The task also wants to redirect stdout. This program does so with [http://netbsd.gw.com/cgi-bin/man-cgi?dup2+2+NetBSD-current dup2(2)]. Had we wanted to directly write to a file, we could open the file with <code>file = fopen(argv[1], "a")</code>, and write to ''file'' instead of ''stdout''.


<lang c>#include <err.h>
<syntaxhighlight lang="c">#include <err.h>
#include <errno.h>
#include <errno.h>
#include <fcntl.h>
#include <fcntl.h>
Line 105: Line 105:
sleep(1); /* Can wake early or drift late. */
sleep(1); /* Can wake early or drift late. */
}
}
}</lang>
}</syntaxhighlight>


<pre>$ make dumper
<pre>$ make dumper
Line 123: Line 123:
{{libheader|go-daemon}}
{{libheader|go-daemon}}
{{works with|Ubuntu 16.04}}
{{works with|Ubuntu 16.04}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 174: Line 174:


work()
work()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 196: Line 196:
{{trans|Python}}
{{trans|Python}}
This is a direct translation of the Python Posix version.
This is a direct translation of the Python Posix version.
<lang Nim>import os, posix, strutils
<syntaxhighlight lang="nim">import os, posix, strutils


let pid = fork()
let pid = fork()
Line 222: Line 222:
while now() < t + initDuration(seconds = 10):
while now() < t + initDuration(seconds = 10):
echo "timer running, $# seconds".format((now() - t).inSeconds)
echo "timer running, $# seconds".format((now() - t).inSeconds)
sleep(1000)</lang>
sleep(1000)</syntaxhighlight>


{{out}}
{{out}}
Line 242: Line 242:
=={{header|Perl}}==
=={{header|Perl}}==
First off, start with a standalone script and let's call it "count.pl"
First off, start with a standalone script and let's call it "count.pl"
<lang perl># 20211217 Perl programming solution
<syntaxhighlight lang="perl"># 20211217 Perl programming solution


use strict;
use strict;
Line 261: Line 261:
print $fh "Sheep number ",$count++," just leaped over the fence ..\n";
print $fh "Sheep number ",$count++," just leaped over the fence ..\n";
$fh->flush();
$fh->flush();
}</lang>
}</syntaxhighlight>
Make sure it works and then we can control/run it in daemon mode with another script
Make sure it works and then we can control/run it in daemon mode with another script
<lang perl>use warnings;
<syntaxhighlight lang="perl">use warnings;
use strict;
use strict;


Line 272: Line 272:
program => '/home/hkdtam/count.pl',
program => '/home/hkdtam/count.pl',
pid_file => '/tmp/counter.pid',
pid_file => '/tmp/counter.pid',
)->run;</lang>
)->run;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 318: Line 318:
Of course there is nothing at all to stop fn from being set to 1 for stdout, or 2 for stderr.<br>
Of course there is nothing at all to stop fn from being set to 1 for stdout, or 2 for stderr.<br>
It is also strongly against the core philosophy of Phix to have or permit anything that would somehow make printf(1,x) do something it does not look like it should be doing, especially given printf(fn,x) has no such ambiguity. Not having to change your code may sound dandy, not being able to tell what your code is doing by looking at it, isn't.
It is also strongly against the core philosophy of Phix to have or permit anything that would somehow make printf(1,x) do something it does not look like it should be doing, especially given printf(fn,x) has no such ambiguity. Not having to change your code may sound dandy, not being able to tell what your code is doing by looking at it, isn't.
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 327: Line 327:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- [close(1) quietly does nothing]</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- [close(1) quietly does nothing]</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<small>(When fn is 1, or the content of log.txt when it is not.)</small>
<small>(When fn is 1, or the content of log.txt when it is not.)</small>
Line 339: Line 339:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(unless (fork)
<syntaxhighlight lang="picolisp">(unless (fork)
(out "file.log"
(out "file.log"
(println *Pid) # First write the daemon's PID to the file
(println *Pid) # First write the daemon's PID to the file
Line 348: Line 348:
(bye) ) # Child terminates after one hour
(bye) ) # Child terminates after one hour


(bye) # Parent terminates immediately</lang>
(bye) # Parent terminates immediately</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
Line 354: Line 354:
if the first argument is "daemon" the program will be restarted with stdout redirected to "foo".
if the first argument is "daemon" the program will be restarted with stdout redirected to "foo".


<lang Pike>int main(int argc, array argv)
<syntaxhighlight lang="pike">int main(int argc, array argv)
{
{
if (sizeof(argv)>1 && argv[1] == "daemon")
if (sizeof(argv)>1 && argv[1] == "daemon")
Line 369: Line 369:
sleep(0.1);
sleep(0.1);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<syntaxhighlight lang="python">
#!/usr/bin/python3
#!/usr/bin/python3
import posix
import posix
Line 402: Line 402:
print("timer running, %s seconds" % str(time.time() - t))
print("timer running, %s seconds" % str(time.time() - t))
time.sleep(1)
time.sleep(1)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require ffi/unsafe)
(require ffi/unsafe)
Line 411: Line 411:
(with-output-to-file "/tmp/foo"
(with-output-to-file "/tmp/foo"
(λ() (for ([i 10]) (displayln (random 1000)) (flush-output) (sleep 1))))
(λ() (for ([i 10]) (displayln (random 1000)) (flush-output) (sleep 1))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6># Reference:
<syntaxhighlight lang="raku" line># Reference:
# https://github.com/hipek8/p6-UNIX-Daemonize/
# https://github.com/hipek8/p6-UNIX-Daemonize/


Line 431: Line 431:
sleep(1);
sleep(1);
spurt $output, DateTime.now.Str~"\n", :append;
spurt $output, DateTime.now.Str~"\n", :append;
}</lang>
}</syntaxhighlight>
{{out}}<pre>root@ubuntu:~# su - david
{{out}}<pre>root@ubuntu:~# su - david
david@ubuntu:~$ ./dumper.p6
david@ubuntu:~$ ./dumper.p6
Line 484: Line 484:
=={{header|Sidef}}==
=={{header|Sidef}}==
When the "daemon" argument is specified, a fork of the program is created with its STDOUT redirected into the file "foo.txt", and the main process is exited.
When the "daemon" argument is specified, a fork of the program is created with its STDOUT redirected into the file "foo.txt", and the main process is exited.
<lang ruby>var block = {
<syntaxhighlight lang="ruby">var block = {
for n in (1..100) {
for n in (1..100) {
STDOUT.say(n)
STDOUT.say(n)
Line 501: Line 501:


STDERR.say("Normal mode")
STDERR.say("Normal mode")
block.run</lang>
block.run</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with |Smalltalk/X}}
{{works with |Smalltalk/X}}
<lang smalltalk>#! /usr/bin/env stx --script
<syntaxhighlight lang="smalltalk">#! /usr/bin/env stx --script
(pid := OperatingSystem fork) == 0 ifTrue:[
(pid := OperatingSystem fork) == 0 ifTrue:[
Stdin close.
Stdin close.
Line 520: Line 520:
Stdout showCR: e'forked new process pid={pid}; now exiting'.
Stdout showCR: e'forked new process pid={pid}; now exiting'.
OperatingSystem exit:0
OperatingSystem exit:0
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>bash-3.2$ ./daemon.st
<pre>bash-3.2$ ./daemon.st
Line 537: Line 537:
Tcl doesn't come with tools for converting the process into a daemon, but can build them easily enough. Here's the BSD daemon function mapped into a Tcl command in a package.
Tcl doesn't come with tools for converting the process into a daemon, but can build them easily enough. Here's the BSD daemon function mapped into a Tcl command in a package.
{{libheader|Critcl}}
{{libheader|Critcl}}
<lang tcl>package provide daemon 1
<syntaxhighlight lang="tcl">package provide daemon 1
package require critcl
package require critcl


Line 550: Line 550:
}
}
return TCL_OK;
return TCL_OK;
}</lang>
}</syntaxhighlight>
These tools can then be used to solve this task:
These tools can then be used to solve this task:
<lang tcl>### Command line argument parsing
<syntaxhighlight lang="tcl">### Command line argument parsing
if {$argc < 1} {
if {$argc < 1} {
puts "usage: $argv0 file ?message...?"
puts "usage: $argv0 file ?message...?"
Line 571: Line 571:
proc every {ms body} {eval $body; after $ms [info level 0]}
proc every {ms body} {eval $body; after $ms [info level 0]}
every 1000 {puts "[clock format [clock seconds]]: $message"}
every 1000 {puts "[clock format [clock seconds]]: $message"}
vwait forever</lang>
vwait forever</syntaxhighlight>
On Windows, there is a commercial extension to Tcl which allows a script to be installed as a service. Such a script would be much like the one above, but without the daemonization section as that has become a property of the runtime.
On Windows, there is a commercial extension to Tcl which allows a script to be installed as a service. Such a script would be much like the one above, but without the daemonization section as that has become a property of the runtime.


Line 579: Line 579:


The following script is based on the C example though modified a little to run on Ubuntu 20.04.
The following script is based on the C example though modified a little to run on Ubuntu 20.04.
<lang ecmascript>/* dumper.wren */
<syntaxhighlight lang="ecmascript">/* dumper.wren */


import "./date" for Date
import "./date" for Date
Line 639: Line 639:
System.print(UT2Date.call(C.time))
System.print(UT2Date.call(C.time))
C.sleep(1)
C.sleep(1)
}</lang>
}</syntaxhighlight>
<br>
<br>
We now embed this in the following C program, compile and run it.
We now embed this in the following C program, compile and run it.
<lang c>/* gcc dumper.c -o dumper -lwren -lm */
<syntaxhighlight lang="c">/* gcc dumper.c -o dumper -lwren -lm */


#include <fcntl.h>
#include <fcntl.h>
Line 791: Line 791:
free(script);
free(script);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}