E
E
egorggegor2021-02-24 18:32:15
linux
egorggegor, 2021-02-24 18:32:15

Why is the daemon not running?

Hello.
Wrote the following daemon, it doesn't work. I assume this is due to the closing of I / O streams, but I don’t fully understand what needs to be fixed to make it work.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char* argv[])
{
  int fd;
  pid_t process_id = 0;
  pid_t sid = 0;

  process_id = fork();

  if (process_id < 0)
  {
    printf("fork failed!\n");
    exit(1);
  }

  if (process_id > 0)
  {
    printf("process_id of child process %d \n", process_id);
    exit(0);
  }

  umask(0);
  sid = setsid();
  if(sid < 0)
  {
    exit(1);
  }

  chdir("/");

  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  while(1) {
    fd = open("/dev/mydev", O_RDONLY);
    read(fd, &buf, 7);
    close(fd);
  }
  return EXIT_SUCCESS;
}


Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Dubrovin, 2021-02-25
@egorggegor

1. In read, you should definitely pass buf and not &buf (you can’t say for sure because there is no description)
2. Depending on how you start the process, the child process may receive SIGHUP when the parent process is closed or SIGPIPE on printf, it is worth adding signal handlers before fork().

V
Vitsliputsli, 2021-02-24
@Vitsliputsli

Missing at least:

#include <fcntl.h>

char buf[7];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question