2012-09-26 3 views
0

데몬 프로그래밍에 대해 읽었을 때 온라인 (예 : RS232, usb, 이더넷) 인 경우 장치를 감지 할 필요가 있다고 생각합니다. 웹 서비스 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이 연결되어 있지 않아 오프라인으로 인쇄합니다.

내 장치를 검색하는 다른 방법이 있습니까?

감사합니다,

답변

1

는 udev가있는 경우, 당신은 당신의 장치를 감지하고 모니터링 할 수 libudev을 사용할 수 있습니다. Checkout 튜토리얼을 signal11에서 확인하십시오.

+0

안녕하세요. libudev를 사용하고 계셔서 고마워요. 그렇지만 어떻게하면 usleep을 사용하지 않고도 모니터링 할 수 있습니다. 새 장치가 연결되었을 때만 깨우쳐서 잠을 잘 자지 않게하십시오. – demic0de

+0

@ demic0de : usleep()을 사용할 필요가 없습니다. 튜토리얼에서는 설명 용도로만 사용되었습니다. 코드에서 withouth usleep()을 잘 수행해야합니다. – Maciej

관련 문제