1

I get this warning while compiling my program. daemon() is declared in unistd.h and its included. How to fix this or make it disappear?

error:

dcron.c: In function 'main':
dcron.c:35:4: warning: implicit declaration of function 'daemon' [-Wimplicit-function-declaration]
    if (daemon(1, 0) != 0) {
    ^

part of program:

if (daemon(1, 0) != 0) {
   fprintf(stderr, "error: failed to daemonize\n");
   syslog(LOG_NOTICE, "error: failed to daemonize");
   return 1;
}

setup: gcc4.8.2, glibc2.19 CFLAGS=-std=c99 -Wall -Wpedantic -Wextra

Ari Malinen
  • 576
  • 2
  • 6
  • 20
  • What OS is this? The daemon() function is in that header on Linux, but it is not a POSIX function, and won't necessarily be there on other operating systems. – Ernest Friedman-Hill Jun 11 '14 at 11:43

2 Answers2

3

You need to add the relevant header file and enable the _BSD_SOURCE feature test macro:

#define _BSD_SOURCE
#include <unistd.h>

From man 3 daemon:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

daemon(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

Community
  • 1
  • 1
ouah
  • 142,963
  • 15
  • 272
  • 331
2

On Linux daemon() is made available by #defineing either

  • _XOPEN_SOURCE
  • _BSD_SOURCE

by doing

#define _XOPEN_SOURCE 

or

#define _BSD_SOURCE 

before #includeing

#include <unistd.h>

or by adding -D _XOPEN_SOURCE or -D _BSD_SOURCE to the compilation command.

alk
  • 69,737
  • 10
  • 105
  • 255
  • Thanks. On my system it was #define __USE_BSD – Ari Malinen Jun 11 '14 at 11:59
  • 1
    Do **not** set double-underscored-prefixed defines directly. They are for internal use only! Setting them from your source might lead to unexpected results. Use `_BSD_SOURCE` to have __USE_BSD` defined. – alk Jun 11 '14 at 12:01
  • Nowadays (gcc 9.3.0), when _BSD_SOURCE is deprecated, we can use _DEFAULT_SOURCE. – kmalarski Feb 15 '22 at 13:51