/******************************************************************************** **函数名称: **函数功能: **函数参数: **返 回 值: **********************************************************************************/ int bt_serial_open(const char *serial_name, int baudrate) { int fd = -1; int res = 0; pthread_t thread_id; fd = open(serial_name,O_RDWR | O_NOCTTY | O_NDELAY); if (fd > 0) { if (set_serial_opts(fd, baudrate, 8, 'N', 1) == -1) { return -1; } FD_ZERO(&read_fds); } return fd; }
int open_serial_obj(obj_t *serial) { /* (Re)opens the specified 'serial' obj. * Returns 0 if the serial console is successfully opened; o/w, returns -1. * * FIXME: Check to see if "downed" serial consoles are ever resurrected. */ int fd; int flags; struct termios tty; assert(serial != NULL); assert(is_serial_obj(serial)); if (serial->fd >= 0) { write_notify_msg(serial, LOG_INFO, "Console [%s] disconnected from \"%s\"", serial->name, serial->aux.serial.dev); set_tty_mode(&serial->aux.serial.tty, serial->fd); if (close(serial->fd) < 0) /* log err and continue */ log_msg(LOG_WARNING, "Unable to close [%s] device \"%s\": %s", serial->name, serial->aux.serial.dev, strerror(errno)); serial->fd = -1; } flags = O_RDWR | O_NONBLOCK | O_NOCTTY; if ((fd = open(serial->aux.serial.dev, flags)) < 0) { log_msg(LOG_WARNING, "Unable to open [%s] device \"%s\": %s", serial->name, serial->aux.serial.dev, strerror(errno)); goto err; } if (get_write_lock(fd) < 0) { log_msg(LOG_WARNING, "Unable to lock [%s] device \"%s\"", serial->name, serial->aux.serial.dev); goto err; } if (!isatty(fd)) { log_msg(LOG_WARNING, "[%s] device \"%s\" not a terminal", serial->name, serial->aux.serial.dev); goto err; } /* According to the UNIX Programming FAQ v1.37 * <http://www.faqs.org/faqs/unix-faq/programmer/faq/> * (Section 3.6: How to Handle a Serial Port or Modem), * systems seem to differ as to whether a nonblocking * open on a tty will affect subsequent read()s. * Play it safe and be explicit! */ set_fd_nonblocking(fd); set_fd_closed_on_exec(fd); /* * Note that while the initial state of the console dev's termios * are saved, the 'opts' settings are not. This is because the * settings do not change until the obj is destroyed, at which time * the termios is reverted back to its initial state. * * FIXME: Re-evaluate this thinking since a SIGHUP should attempt * to resurrect "downed" serial objs. */ get_tty_mode(&serial->aux.serial.tty, fd); get_tty_raw(&tty, fd); set_serial_opts(&tty, serial, &serial->aux.serial.opts); set_tty_mode(&tty, fd); serial->fd = fd; serial->gotEOF = 0; /* * Success! */ write_notify_msg(serial, LOG_INFO, "Console [%s] connected to \"%s\"", serial->name, serial->aux.serial.dev); DPRINTF((9, "Opened [%s] serial: fd=%d dev=%s bps=%d.\n", serial->name, serial->fd, serial->aux.serial.dev, bps_to_int(serial->aux.serial.opts.bps))); return(0); err: if (fd >= 0) { close(fd); /* ignore errors */ } return(-1); }