Заблокировать порт ttyACM0

Модератор: Модераторы разделов

Ответить
wade
Сообщения: 6

Заблокировать порт ttyACM0

Сообщение wade »

Приветствую.
Для того чтобы устройство на ttyACM0 правильно функционировало, необходимо чтобы программа открывала его в монопольном режиме, например
program открывает /dev/ttyACM0, тогда команда echo "aaaa" > /dev/ttyACM0 должна закончиться неудачей. Minicom это делает, а у меня не получается.
Вот код открытия:

Код: Выделить всё

fd = open(device, O_RDWR | O_EXCL );
      if (fd == -1)
      {
       /*
    * Could not open the port.
    */

    perror(device);
          //return NULL;
      }
    //fcntl(fd, F_SETFL, FNDELAY);

    struct flock lock;
    lock . l_type = F_WRLCK;
    lock . l_whence = SEEK_SET;
    lock . l_start = 0;
    lock . l_len = 0;

    if (fcntl (fd, F_SETLK, & lock) < 0) {

      perror(device);
      //return NULL;
    }

    int status;

    ioctl(fd, TIOCMGET, &status);
    status &= ~TIOCM_RTS;
    status &= ~TIOCM_DTR;
    status &= ~TIOCM_CTS;
    status &= ~TIOCM_DSR;

    if (ioctl(fd, TIOCMSET, &status))
    {
      perror("ioctl");
      //return 0;
    }

    struct termios options;

    /*
     * Get the current options for the port...
     */

    tcgetattr(fd, &options);

    cfsetispeed(&options, baud_rate);
    cfsetospeed(&options, baud_rate);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CRTSCTS;
    options.c_oflag &= ~OPOST; //raw output

    options.c_lflag &= ~(ICANON | ECHO | ISIG);

    /*
     * Enable the receiver and set local mode...
     */

    options.c_cflag |= (CLOCAL | CREAD | baud_rate);

    /*
     * Set the timeouts VMIN is the minimum amount of characters to read
     */

    //options.c_cc[VMIN] = 0;

    /*
     * The amount of time to wait for the amount of data specified by VMIN in tenths of a second
     */

    //options.c_cc[VTIME] = 0;

    /*
     * Set the new options for the port...
     */

    tcsetattr(fd, TCSANOW, &options);


Подскажите, что не так. Либо кусок кода.где работает блокировка. Спасибо
Спасибо сказали:
MrClon
Сообщения: 838
ОС: Ubuntu 10.04, Debian 7 и 6

Re: Заблокировать порт ttyACM0

Сообщение MrClon »

Здравствуйте, sysenter, Вы писали:

S>Здравствуйте, Аноним, Вы писали:

А>>Может реализовать монопольный доступ ? И каким образом ?
А>>Желательно решение на ANSI C.

S>Платформозависимое API, только так, Win — LockFile, LockFileEx; Linux — fcntl, flock.

Если не на на ANSI C, то есть портабельная&#153; обертка: boost::interprocess::file_lock


В Linux ещё есть lockf(), позволяет избегать взаимной блокировки файлов возвращая EDEADLK.

via http://www.rsdn.ru/forum/cpp/4409836.flat.aspx из выдачи гугла по запросу «linux монопольный доступ к файлу». Авось поможет
Спасибо сказали:
Аватара пользователя
Bizdelnick
Модератор
Сообщения: 20794
Статус: nulla salus bello
ОС: Debian GNU/Linux

Re: Заблокировать порт ttyACM0

Сообщение Bizdelnick »

wade писал(а):
12.01.2012 09:53
кусок кода.где работает блокировка.

Так сами же пишете:
wade писал(а):
12.01.2012 09:53
Minicom это делает

Найти слабо?

Код: Выделить всё

void lockfile_remove(void)
{
  if (portfd_is_socket)
    return;

#if !HAVE_LOCKDEV
  if (lockfile[0])
    unlink(lockfile);
#else
  ttyunlock(dial_tty);
#endif
}

int lockfile_create(void)
{
  int n;

  if (portfd_is_socket)
    return 0;

#if !HAVE_LOCKDEV
  if (!lockfile[0])
    return 0;

  int fd;
  n = umask(022);
  /* Create lockfile compatible with UUCP-1.2 */
  if ((fd = open(lockfile, O_WRONLY | O_CREAT | O_EXCL, 0666)) < 0) {
    werror(_("Cannot create lockfile!"));
  } else {
    // FHS format:
    char buf[12];
    snprintf(buf, sizeof(buf),  "%10d\n", getpid());
    buf[sizeof(buf) - 1] = 0;
    write(fd, buf, strlen(buf));
    close(fd);
  }
  umask(n);
  return 0;
#else
  n = ttylock(dial_tty);
  if (n < 0) {
    fprintf(stderr, _("Cannot create lockfile for %s: %s\n"), dial_tty, strerror(-n));
  } else if (n > 0) {
    fprintf(stderr, _("Device %s is locked.\n"), dial_tty);
  }
  return n;
#endif
}

P.S. Не забывайте, что лицензия GPLv2+ со всеми вытекающими.
P.P.S. Да, тут используется lockdev.
man lockdev
Пишите правильно:
в консоли
вку́пе (с чем-либо)
в общем
вообще
в течение (часа)
новичок
нюанс
по умолчанию
приемлемо
проблема
пробовать
трафик
Спасибо сказали:
wade
Сообщения: 6

Re: Заблокировать порт ttyACM0

Сообщение wade »

Bizdelnick, к сожалению как ни крутил этот кусок из миникома так пока не разобрался. Спасибо за совет, сейчас попробую
Спасибо сказали:
Ответить