| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <string.h>
- #define DEVICE_FILE "/dev/gpio_led"
- int main()
- {
- int fd;
- char write_buf[100] = "Hello from user space!";
- char read_buf[100] = "\0";
- // 打开设备文件
- fd = open(DEVICE_FILE, O_RDWR);
- if (fd < 0) {
- perror("open");
- return -1;
- }
- // 从设备读取数据
- ssize_t read_bytes = read(fd, read_buf, sizeof(read_buf)); // 尝试读取更多数据
- if (read_bytes < 0) {
- perror("read");
- close(fd);
- return -1;
- } else if (read_bytes == 0) {
- printf("No data read from the device.\n");
- } else {
- read_buf[read_bytes] = '\0';
- printf("Read from the device: %s\n", read_buf);
- memset(read_buf, 0, sizeof(read_buf)); // 将 read_buf 数组的所有元素设置为 0
- }
- // 向设备写入数据
- ssize_t written = write(fd, write_buf, sizeof(write_buf));
- if (written < 0) {
- perror("write");
- close(fd);
- return -1;
- } else {
- printf("Wrote %zd bytes to the device.\n", written);
- }
- // 从设备读取数据
- ssize_t read_bytes1 = read(fd, read_buf, 40); // 继续读取更多数据
- if (read_bytes1 < 0) {
- perror("read");
- close(fd);
- return -1;
- } else if (read_bytes1 == 0) {
- printf("No data read from the device.\n");
- } else {
- printf("Read from the device: %s\n", read_buf);
- }
- // 关闭设备文件
- close(fd);
- return 0;
- }
|