通过多进程获取树莓派温度
在linux里面通过调用ds18b20可以得到传感器温度,通过这一理论写出获取树莓派温度的多进程代码。
通过这一指令可以调取温度。我们就可以通过多进程c代码来实现温度的文件获得,通过system函数和dup2函数对输入进行改变,再打开文件io来获取温度
代码如下:
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <ctype.h>
9
10 int main(int main, char *argv[])
11 {
12 int pid = -1;
13 int fd = -1;
14 int rv = -1;
15 char buf[1024];
16 char cmd_buf[256];
17 char *interface="ds18b20";
18 if((fd=open("test.txt", O_RDWR|O_CREAT|O_TRUNC, 0666))<0)
19 {
20 printf("file open failure",strerror(errno));
22 pid = fork();
23 if(pid < 0)
24 {
25 printf("fork() create child process failure: %s\n", strerror(errno)) ;
26 return -1;
27 }
28 else if( pid == 0 )
29 {
30 dup2(fd, 1);
31 system("ds18b20");
32 }
33 else
34 {
35 sleep(2);
36 memset(buf, 0, sizeof(buf));
37 lseek(fd, 0, SEEK_SET);
38 rv=read(fd, buf, sizeof(buf));
39 printf("Read %d bytes data after lseek:\n %s", rv, buf);
40 }
41 return 0;
42 }
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20210201144148984.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTIwOTMzMQ==,size_16,color_FFFFFF,t_70#pic_center)
文件就可获得树莓派温度