我的程序如下:
程序阻塞在read函数中,不能返回......
#include
#include
#include
#include
#include
// Set baud rate
int set_speed(int fd, speed_t speed)
{
struct termios opt;
tcgetattr(fd, &opt);
tcflush(fd, TCIOFLUSH);
cfsetispeed(&opt, speed);
cfsetospeed(&opt, speed);
if (tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("tcsetattr\n");
return 0;
}
tcflush(fd, TCIOFLUSH);
return 1;
}
// Set data bits, stop bits, and parity
int set_parity(int fd, int databits, int parity, int stopbits)
{
struct termios opt;
if (tcgetattr(fd, &opt) != 0)
{
perror("tcgetattr\n");
return 0;
}
opt.c_cflag &= ~CSIZE;
switch (databits)
{
case 7:
opt.c_cflag |= ~CS7;
break;
case 8:
opt.c_cflag |= ~CS8;
break;
default:
fprintf(stderr, "Unsupported data bits\n");
return 0;
}
switch (parity)
{
case 'n':
case 'N':
opt.c_cflag &= ~PARENB;
opt.c_iflag &= ~INPCK;
break;
case 'o':
case 'O':
opt.c_cflag |= (PARODD | PARENB);
opt.c_iflag |= INPCK;
break;
case 'e':
case 'E':
opt.c_cflag |= PARENB;
opt.c_cflag &= ~PARODD;
opt.c_iflag |= INPCK;
break;
case 'S':
case 's':
opt.c_cflag &= ~PARENB;
opt.c_cflag &= ~CSTOPB;
break;
default:
fprintf(stderr, "Unsupported parity.\n");
return 0;
}
switch(stopbits)
{
case 1:
opt.c_cflag &= ~CSTOPB;
break;
case 2:
opt.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr, "Unsupported stop bits\n");
return 0;
}
tcflush(fd, TCIFLUSH);
if (tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("tcsetattr\n");
return 0;
}
return 1;
}
int main()
{
int fd = open("/dev/modem", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
printf("Can't open /dev/modem\n");
return -1;
}
struct termios opt;
// Set terminal attribute
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &opt);
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_iflag &= ~( ICANON | ECHO | ECHOE | ISIG);
opt.c_oflag &= ~OPOST;
opt.c_cc[VMIN] = 0;
opt.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &opt);
// Set speed
if (set_speed(fd, B115200) == 0)
{
fprintf(stderr, "Set speed failed.\n");
return -1;
}
// Set databits, parity, stopbits
if (set_parity(fd, 8, 'N', 1) == 0)
{
fprintf(stderr, "Set parity failed.\n");
return -1;
}
char buf[128] = {0};
strcpy(buf, "AT\r");
int len = strlen(buf);
if (len != write(fd, buf, len))
{
printf("Write failed.\n");
return -1;
}
printf("About to read...\n");
len = read(fd, buf, 2);
printf("Read %d bytes.\n", len);
buf[len] = 0;
printf("buf = %s\n", buf);
close(fd);
return 0;
}