一.HTML文件
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>LED_device</title>
</head>
<body>
<form action="/cgi-bin/led.cgi" method="post">
<p>LED设备号</p>
<input type="text" name="name">
<p>操作</p>
<input type="text" name="number">
<input type="submit" value="提交">
</form>
<a href="/cgi-bin/test.cgi"> 跳转到test.cgi </a>
</body>
</html>
二.led.c文件
cpp
#include <stdio.h>
#include "cgic.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define LED_DEVICE "/sys/class/leds/sys-led/brightness"
#define LED_DEVICE0 1
#define LED_ON 1
#define LED_OFF 0
int cgiMain()
{
char name[241] = {0};
char number[241] = {0};
int led_device = 0;
int led_operation = 0;
int fd = -1;
fd = open(LED_DEVICE,O_RDWR);
if(0 > fd)
{
printf("led device open failed\n");
}
cgiHeaderContentType("text/html");
fprintf(cgiOut, "<HTML>\n");
fprintf(cgiOut,"<HEAD>\n");
fprintf(cgiOut, "<TITLE>LED CGI</TITLE>\n");
fprintf(cgiOut,"<meta charset='utf-8'>\n");
fprintf(cgiOut,"</HEAD>\n");
fprintf(cgiOut,"<BODY>\n");
fprintf(cgiOut, "<H1>LED CGI</H1>\n");
cgiFormString("name",name,241); //获取名为name的数据
cgiFormString("number",number,241); //获取名为number的数据
fprintf(cgiOut,"<H2>name=%s</H2>\n",name);
fprintf(cgiOut,"<H2>number=%s</H2>\n",number);
fprintf(cgiOut, "<a href='/led.html'>回到LED控制界面</a>\n\n");
led_device = atoi(name);
led_operation = atoi(number);
if((led_device == LED_DEVICE0) && (led_operation == LED_ON))
{
fprintf(cgiOut,"<p>开灯操作成功</p>");
}
else if((led_device == LED_DEVICE0) && (led_operation == LED_OFF))
{
fprintf(cgiOut,"<p>关灯操作成功</p>\n");
}
else
{
fprintf(cgiOut,"<p>操作指令有误</p>\n");
}
fprintf(cgiOut, "</BODY>\n");
/* 对比设备和操作指令,使用write函数向LED文件写入数据以控制灯的亮灭 */
if(led_device == LED_DEVICE0 && led_operation == LED_ON)
{
write(fd,"1",1);
}
else if(led_device == LED_DEVICE0 && led_operation == LED_OFF)
{
write(fd,"0",1);
}
close(fd);
fprintf(cgiOut, "</HTML>\n");
return 0;
}
在led.html网页中输入设备号为1,操作指令为1则可开灯,操作指令为0则关灯