使用 unistd.h 和 C 写入 mac OSX 10.9.3 上的串行端口

p0f*_*0fi 2 c macos serial-port

我正在尝试使用标准 C 中的 unistd.h 将一些字节写入 mac OSX 10.9.3 上的串行端口。我知道有一个类似的主题,但它已经 4 岁了,并且存在不同的问题,所以请原谅我开始一个新线程。

我的问题是 write(); 函数,它总是以 -1 的值返回。打开我的端口的代码如下:

curByte = 0;
numBytes = 0;
bool blocking = false;
//Settings structure old and new
struct termios newtio;

fd = open(port, O_RDWR | O_NOCTTY | (blocking ? 0 : O_NDELAY));
if (fd < 0)
{
    return PORT_ERROR;
}
bzero(&newtio, sizeof(newtio));

if (cfsetispeed(&newtio, BDR_ESP3) != 0)
    return PORT_ERROR;
if (cfsetospeed(&newtio, BDR_ESP3) != 0)
    return PORT_ERROR;

newtio.c_cflag &= ~PARENB;
newtio.c_cflag &= ~CSTOPB;
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |= CS8;
newtio.c_cflag &= ~CRTSCTS;

//Hardware control of port
newtio.c_cc[VTIME] = blocking ? 1 : 0; // Read-timout 100ms when blocking
newtio.c_cc[VMIN] = 0;

tcflush(fd, TCIFLUSH);
//Acquire new port settings
if (tcsetattr(fd, TCSANOW, &newtio) != 0)
    puts(strerror(errno));
return OK;
Run Code Online (Sandbox Code Playgroud)

我可以毫无问题地打开端口,但是一旦我尝试使用以下方法向端口写入一个字节:

{
int res;

if (fd == -1)
    return PORT_ERROR;
    res = write(fd, &u8TxByte, 1);
if (res == -1){
    printf("Error writing to port - %s(%d).\n", strerror(errno), errno);
}
if (res == 1)
    printf("Writing to port succeeded!");
    return OK;

return ERROR;
 }
Run Code Online (Sandbox Code Playgroud)

我不断收到这样的错误输出:

写入端口时出错 - 资源暂时不可用 (35)。

快把我逼疯了!因为相同的代码实际上可以在 Linux 上运行,那么这里与 OSX 的区别在哪里?资源暂时不可用是什么意思?

我希望我能很好地描述我的问题,有人可以帮助我!谢谢!

mfr*_*fro 6

使用相应的/dev/cu.xxx设备,您的程序可能会运行。

/dev/tty.xxx 用于 OS/X 上的传入连接,并且只有在断言 DCD 时才有效。