我需要编写遵循以下步骤的程序:
- 启动程序(守护进程)
- 等待(睡眠,阻塞)直到我有 wifi 连接
- 从服务器发送/获取一些数据
- 等到wifi连接断开
- 转到 2
第 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 功能?
PS这是我在这里的第一篇文章,希望一切都好。