DBPST
DBPST

Reputation: 23

Can't open a ttyUSB port in a daemon

I have a problem with using a port within a daemon in linux. I use open from fcntl.h like serHandle_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); and I get 0 as result when I use it within a daemon. When I use it outside a daemon everything works fine. I've set sudo chmod 666 /dev/ttyUSB0.

Do you have some idea what the problem may be? Maybe permissions? Even if I start the daemon as superuser I still get 0 as a result from open.

Below you can see a code snippet of my class method that should initialize the daemon:

Bool DaemonStarter::initialize()
{
  isInitialized_ = false;
  if (workingDirectory_ == "" ||
      !boost::filesystem3::exists(workingDirectory_))
    return false;

  Bool res = true;
  ::setlogmask(LOG_UPTO(LOG_NOTICE));
  ::openlog(name_.c_str(), LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);

  pid_t pid, sid;
  pid = fork();

  if (pid < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }

  if (pid > 0)
  {
    res = res && true;
    ::exit(EXIT_SUCCESS);
  }

  ::umask(0);

  sid = ::setsid();
  if (sid < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }

  if ((chdir(workingDirectory_.c_str())) < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }

  for (UInt i = ::sysconf (_SC_OPEN_MAX); i > 0; i--)
        ::close (i);

  ::umask(0);

  ::close(STDIN_FILENO);
  ::close(STDOUT_FILENO);
  ::close(STDERR_FILENO);
  isInitialized_ = res;
  return res;
}

Upvotes: 0

Views: 361

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409196

When you close the standard file descriptors (stdin/stdout/stderr) those file descriptors may then be reused by the next call to open. So when open returns 0 it's quite normal.

If open would have failed, it would have returned -1.

I recommend you read the open manual page more closely.

Upvotes: 1

Drew McGowen
Drew McGowen

Reputation: 11706

From the man pages of open: "open() and creat() return the new file descriptor, or -1 if an error occurred"

0 is a perfectly valid file descriptor (and for non-daemon applications, is your stdin file descriptor). If open were to fail, it would return -1, so your code is working fine.

Upvotes: 2

Related Questions