我们有wifi连接的时刻

时间:2011-02-15 10:14:24

标签: c linux embedded inotify

我需要编写遵循以下步骤的程序:

  1. 启动程序(守护程序)
  2. 等待(睡眠,阻止)直到我有wifi连接
  3. 从服务器发送/获取一些数据
  4. 等到wifi连接断开
  5. 转到2
  6. 第2步出现问题。我不知道如何在建立网络连接时抓住时机。有/proc/net/wireless entry,其中显示有关可用无线连接的信息,但尝试使用inotify监控它并没有成功。网络连接是异步建立的。

    这是我的带有inotify的测试代码(主要从R.Loves书中复制):

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/inotify.h>
    #include <sys/select.h>
    
    #define BUF_LEN 1024
    
    int
    main() {
    
        int fd, wd, rc;
        char buf[BUF_LEN];
        ssize_t len, i = 0;
        static fd_set read_fds;
    
        fd = inotify_init();
        if (fd == -1) {
            perror("inotify_init");
            exit(EXIT_FAILURE);
        }
    
        wd = inotify_add_watch(fd, "/proc/net/wireless", IN_ALL_EVENTS);
        if (wd == -1) {
            perror("inotify_add_watch");
            exit(EXIT_FAILURE);
        }
    
        for (;;) {
    
            FD_ZERO(&read_fds);
            FD_SET(wd, &read_fds);
            rc = select(wd + 1, &read_fds, NULL, NULL, NULL);
            if (rc == -1)
                perror("select");
    
            len = read(fd, buf, BUF_LEN);
            while (i < len) {
                struct inotify_event *event = (struct inotify_event *) &buf[i];
                printf("wd=%d mask=%d cookie=%d len=%d dir=%s\n",
                    event->wd, event->mask, event->cookie, event->len, 
                    (event-> mask & IN_ISDIR) ? "yes" : "no");
                if (event->len)
                    printf("name=%s\n", event->name);
    
                i += sizeof(struct inotify_event) + event->len;
            }
    
            sleep(1);
        }
    
        return 0;
    }
    

    当我cat /proc/net/wireless

    时,它只会抓住它

    问题:当我运行网络连接(wifi),仅使用Linux功能时,如何捕捉时刻?

    P.S。这是我在这里发表的第一篇文章,希望一切顺利。

1 个答案:

答案 0 :(得分:1)

您可以通过netlink接口rtnetlink检测网络连接(不仅仅是wifi)何时可以链接就绪。

这不是一个简单的编程接口,因此您可能希望调用“ip monitor link”进程。如果您看到界面具有LOWER_UP标志,则表示已准备好发送/接收(编辑:您可能还想检查NO_CARRIER标志是否缺席;请参阅Simon的评论)。

但是,还存在一个问题,即您可能遇到像NetworkManager这样的守护程序的竞争条件,如果这样配置,它将在链接可用后尝试获取IP地址。