СоНоты

Демонизация


int daemonize(void){
  char *ptty0;
  char *ptty1;
  char *ptty2;
  int fd;

  if (((ptty0 = ttyname(0)) == NULL) || ((ptty1 = ttyname(1)) == NULL) ||
      ((ptty2 = ttyname(2)) == NULL))
    return -1;

  if (fork() != 0)
    exit(1);
  close(0);
  close(1);
  close(2);
  setsid();

  if ((fd = open("/dev/null", O_RDONLY)) == -1)    return -1;

  if (dup2(fd, 0) == -1)    return -1;

  if ((fd = open(ptty1, O_WRONLY)) == -1)    return -1;

  if (dup2(fd, 1) == -1)    return -1;

  if (close(fd) == -1)    return -1;

  if ((fd = open(ptty2, O_WRONLY)) == -1)    return -1;

  if (dup2(fd, 2) == -1)    return -1;

  if (close(fd) == -1)    return -1;

  return 0;
}