0
我阅读了有关守护程序编程的内容,我想我会需要这个来检测我的设备,如果在线或不在,例如(RS232,USB,以太网)。然后在web服务PHP中获取。与设备交谈的守护程序
该网站的代码。 http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
我添加了一些部分来测试,如果我可以检测设备。
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
int devfd;
int main(int argc, char *argv[]) {
int c;
while((c=getopt(argc,argv,"s")) != -1)
switch(c){
case 's': devfd = open("/dev/ttyUSB0", O_RDWR);
if(devfd==-1){
printf("offline\n");
}
else{
printf("online\n");
}
break;
default: printf("Wrong command\n");
}
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Daemon-specific initialization goes here */
/* The Big Loop */
while (1) {
}
exit(EXIT_SUCCESS);
}
添加此代码..
while((c=getopt(argc,argv,"s")) != -1)
switch(c){
case 's': devfd = open("/dev/ttyUSB0", O_RDWR);
if(devfd==-1){
printf("offline\n");
}
else{
printf("online\n");
}
break;
default: printf("Wrong command\n");
}
这样做时,像这样的在终端中。
./daemon -s //由于设备USB0未连接,因此打印离线。
是否有另一种方法可以检测我的设备?
感谢,
嗨,谢谢你,现在我将使用libudev ...但我怎么监视它,而不使用usleep ..说,只有当一个新的设备连接,所以它使更聪明,没有睡眠醒来。 – demic0de
@ demic0de:你不必使用usleep()。在教程中,它仅用于说明目的。如果没有usleep()在你的代码中,它应该可以正常工作。 – Maciej