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