c - 串口在linux ubuntu中打不开

标签 c linux ubuntu serial-port communication

我无法在 linux ubuntu 中打开串口以开始通信。我试过这个:

int OpenPort(void) {

int fd; 

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

if(fd == -1)
{
  printf("Failed to open port.\n");
}
else
{
    fcntl(fd, F_SETFL, 0);
    printf("Opened!\n");
}

return(fd);
}

int main()
{
  int x = OpenPort();
  printf("%i\n", x);

  exit(0);
}

我是 linux 的新手,在网上找到了这段代码,但它对我不起作用。

最佳答案

您需要以 super 用户/root 身份运行才能访问 linux 中的串口。尝试以 sudo 运行您的二进制文件。如果您可以验证这是问题所在,但您不希望您的进程由 root 用户运行,您可以在代码中使用一些选项来获得 root 权限。这个答案可能对阅读有用 How to programmatically gain root privileges?

关于c - 串口在linux ubuntu中打不开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014711/

相关文章:

c++ - libzmq 和 cppzmq 之间以及 zmq.h 和 zmq.hpp 之间的区别?

c - 如何正确调试用 C 编写的共享库?

c - 操作系统如何保证安全?

php - 如何检测动画 GIF 的每秒滴答声?

ubuntu - 如何在 Ubuntu 上安装 Postman Native?

c - 编译时找不到融合函数

c++ - COM SDK 引用文档应该用什么语法编写?

c - 堆栈上的结构 - 字段已初始化?

c - C中的评估&&运算符

linux - msync 是否像 ext3 上的 fsync 一样将文件系统上的所有文件同步到磁盘?