ledUserApp.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #define DEVICE_FILE "/dev/gpio_led"
  7. int main()
  8. {
  9. int fd;
  10. char write_buf[100] = "Hello from user space!";
  11. char read_buf[100] = "\0";
  12. // 打开设备文件
  13. fd = open(DEVICE_FILE, O_RDWR);
  14. if (fd < 0) {
  15. perror("open");
  16. return -1;
  17. }
  18. // 从设备读取数据
  19. ssize_t read_bytes = read(fd, read_buf, sizeof(read_buf)); // 尝试读取更多数据
  20. if (read_bytes < 0) {
  21. perror("read");
  22. close(fd);
  23. return -1;
  24. } else if (read_bytes == 0) {
  25. printf("No data read from the device.\n");
  26. } else {
  27. read_buf[read_bytes] = '\0';
  28. printf("Read from the device: %s\n", read_buf);
  29. memset(read_buf, 0, sizeof(read_buf)); // 将 read_buf 数组的所有元素设置为 0
  30. }
  31. // 向设备写入数据
  32. ssize_t written = write(fd, write_buf, sizeof(write_buf));
  33. if (written < 0) {
  34. perror("write");
  35. close(fd);
  36. return -1;
  37. } else {
  38. printf("Wrote %zd bytes to the device.\n", written);
  39. }
  40. // 从设备读取数据
  41. ssize_t read_bytes1 = read(fd, read_buf, 40); // 继续读取更多数据
  42. if (read_bytes1 < 0) {
  43. perror("read");
  44. close(fd);
  45. return -1;
  46. } else if (read_bytes1 == 0) {
  47. printf("No data read from the device.\n");
  48. } else {
  49. printf("Read from the device: %s\n", read_buf);
  50. }
  51. // 关闭设备文件
  52. close(fd);
  53. return 0;
  54. }