Run as a daemon or service: Difference between revisions

Add C, with the rather unnecessary stdout redirection.
m (→‎{{header|Pike}}: formatting)
(Add C, with the rather unnecessary stdout redirection.)
Line 7:
 
Note that in some language implementations it may not be possible to disconnect from the terminal, and instead the process needs to be started with stdout (and stdin) redirected to files before program start. If that is the case then a helper program to set up this redirection should be written in the language itself. A shell wrapper, as would be the usual solution on Unix systems, is not appropriate.
 
=={{header|C}}==
Most daemons have no stdout, but this draft task strangely wants to use stdout, so this program has a weird dup2() call. (Perhaps the task should remove its spurious stdout requirement.)
 
{{libheader|BSD libc}}
<lang c>#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
 
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
 
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
 
/* Open the file before becoming a daemon. */
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
 
/*
* Become a daemon. Lose terminal, current working directory,
* stdin, stdout, stderr.
*/
if (daemon(0, 0) < 0)
err(1, "daemon");
 
/* Redirect stdout. */
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
 
/* Dump clock. */
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
fflush(stdout);
sleep(1); /* Can wake early or drift late. */
}
}</lang>
 
<pre>$ make dumper
cc -O2 -pipe -o dumper dumper.c
$ ./dumper dump
$ tail -f dump
Fri Nov 18 13:50:41 2011
Fri Nov 18 13:50:42 2011
Fri Nov 18 13:50:43 2011
Fri Nov 18 13:50:44 2011
Fri Nov 18 13:50:45 2011
^C
$ pkill -x dumper
$ rm dump</pre>
 
=={{header|Pike}}==
Anonymous user