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设备所以离线打印。

我还有其他方法可以检测我的设备吗?

谢谢,

4

1 回答 1

1

如果它有 udev,您可以使用libudev来检测和监控您的设备。从signal11结帐不错的教程。

于 2012-09-26T08:32:50.183 回答