【发布时间】:2012-10-29 16:17:23
【问题描述】:
我想从我的 c++ 应用程序连接到 Cisco 路由器。 需要它才能获得接口状态。 我的 linux station (Ubuntu) 和路由器通过串口连接。
从 puty 或 minicom 或控制台连接工作。
例如:
root@test:/etc/minicom# cu -l /dev/ttyS0 -s 9600
Connected.
Router#show int summary
*: interface is up
IHQ: pkts in input hold queue IQD: pkts dropped from input queue
OHQ: pkts in output hold queue OQD: pkts dropped from output queue
RXBS: rx rate (bits/sec) RXPS: rx rate (pkts/sec)
TXBS: tx rate (bits/sec) TXPS: tx rate (pkts/sec)
TRTL: throttle count
现在我尝试用 C++(或 C)做同样的事情,但读取挂起。
我的c代码:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <iostream>
#include<stdio.h>
#include<sys/ioctl.h>
#include<unistd.h>
#include<fcntl.h>
using namespace std;
int fd1;
int fd2;
char *buff, *buffer, *bufptr;
int wr, rd, nbytes, tries;
int configure_port(int fd) // configure the port
{
struct termios port_settings; // structure to store the port settings in
bzero(&port_settings, sizeof(port_settings));
cfsetispeed(&port_settings, B9600); // set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
return (fd);
}
int main() {
fd1 = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd1 == -1) {
perror("open_port: Unable to open /dev/ttyS0 – ");
} else {
fcntl(fd1, F_SETFL, 0);
}
printf("Port 1 has been sucessfully opened and %d is the file description\n",fd1);
configure_port(fd1);
wr = write(fd1, "\r", 1);
cout << " wr status " << wr << endl;
wr = write(fd1, "\r", 1);
cout << " wr status " << wr << endl;
wr = write(fd1, "ena\r", 4);
cout << " wr status " << wr << endl;
wr = write(fd1, "show int sum\r", 13);
cout << " wr status " << wr << endl;
rd = read(fd1, buff, 50);
cout << " rd status " << rd << endl;
cout << rd << endl;
return 0;
}
【问题讨论】:
-
你设置好
port_settings了吗?我注意到它没有初始化为零...... -
我的第一个建议是“尝试 cu”(Linux)或“超级终端”(Windows)。但你已经做到了——RS232 连接正常。问:您是否尝试过将“port_settings”初始化为零?
-
@paulsm4 我是新手,你能把'port_settings'解释为0吗?
-
@Useless 如果你想添加 bzero(&port_settings, sizeof(port_settings));比这导致阅读挂起。没有它读取失败
-
好的,首先:读取失败时,错误是什么?其次,如果读取挂起,大概它至少成功等待数据......我认为正确的行尾肯定是
\r?您可以stracecu 和您的进程,比较确切他们都写给/dev/ttyS0...
标签: c linux serial-port cisco hardware-interface