#5
by かずま » 7年前
Linux の場合です。
proc.c
コード:
#include <stdio.h> // fopen, fclose, fprintf, puts
#include <unistd.h> // getpid, sleep
int main(void)
{
pid_t pid = getpid();
char *name = "/tmp/file1.txt";
FILE *fp = fopen(name, "w");
if (!fp) { puts("fopen failed"); return 1; }
for (int i = 0; i < 10; i++) {
fprintf(fp, "%d\n", i);
fflush(fp);
printf("%d: %d %s\n", i, pid, name);
sleep(1);
}
fclose(fp);
}
ino.c
コード:
#include <stdio.h> // popen, pclose
#include <sys/inotify.h> // inotify_init, inotify_add_watch
#include <unistd.h> // read
int main(void)
{
struct inotify_event *ie;
char buf[4096], *p;
int fd, wd, len;
const char *name = "/tmp/file1.txt";
fd = inotify_init();
if (fd < 0) { puts("inotify_init failed"); return 1; }
wd = inotify_add_watch(fd, name, IN_OPEN | IN_CLOSE | IN_MODIFY);
if (wd < 0) { puts("inotifye_add_watch failed"); return 2; }
while ((len = read(fd, buf, sizeof buf)) > 0) {
for (p = buf; p < buf + len; p += sizeof(*ie) + ie->len) {
ie = (struct inotify_event *) p;
if (ie->mask & IN_MODIFY) {
int pid;
FILE *fp;
char cmd[1024];
sprintf(cmd, "lsof -Fp %s", name);
fp = popen(cmd, "r");
if (fp) {
if (fscanf(fp, "p%d", &pid) == 1)
printf("[%s] pid = %d\n", name, pid);
pclose(fp);
}
}
}
}
close(fd);
puts("done");
return 0;
}
端末を 2つ開き、
・端末1で ./proc を実行し、1秒ごとに /tmp/file1.txt を更新
・端末2で ./ino を実行し、/tmp/file1.txt が更新されるたびにプロセスD を表示
・端末1で ./proc を実行し、1秒ごとに /tmp/file1.txt を更新
・端末2で Ctrl-C を入力し、ino を終了
Linux の場合です。
proc.c
[code=c]
#include <stdio.h> // fopen, fclose, fprintf, puts
#include <unistd.h> // getpid, sleep
int main(void)
{
pid_t pid = getpid();
char *name = "/tmp/file1.txt";
FILE *fp = fopen(name, "w");
if (!fp) { puts("fopen failed"); return 1; }
for (int i = 0; i < 10; i++) {
fprintf(fp, "%d\n", i);
fflush(fp);
printf("%d: %d %s\n", i, pid, name);
sleep(1);
}
fclose(fp);
}
[/code]
ino.c
[code=c]
#include <stdio.h> // popen, pclose
#include <sys/inotify.h> // inotify_init, inotify_add_watch
#include <unistd.h> // read
int main(void)
{
struct inotify_event *ie;
char buf[4096], *p;
int fd, wd, len;
const char *name = "/tmp/file1.txt";
fd = inotify_init();
if (fd < 0) { puts("inotify_init failed"); return 1; }
wd = inotify_add_watch(fd, name, IN_OPEN | IN_CLOSE | IN_MODIFY);
if (wd < 0) { puts("inotifye_add_watch failed"); return 2; }
while ((len = read(fd, buf, sizeof buf)) > 0) {
for (p = buf; p < buf + len; p += sizeof(*ie) + ie->len) {
ie = (struct inotify_event *) p;
if (ie->mask & IN_MODIFY) {
int pid;
FILE *fp;
char cmd[1024];
sprintf(cmd, "lsof -Fp %s", name);
fp = popen(cmd, "r");
if (fp) {
if (fscanf(fp, "p%d", &pid) == 1)
printf("[%s] pid = %d\n", name, pid);
pclose(fp);
}
}
}
}
close(fd);
puts("done");
return 0;
}
[/code]
端末を 2つ開き、
・端末1で ./proc を実行し、1秒ごとに /tmp/file1.txt を更新
・端末2で ./ino を実行し、/tmp/file1.txt が更新されるたびにプロセスD を表示
・端末1で ./proc を実行し、1秒ごとに /tmp/file1.txt を更新
・端末2で Ctrl-C を入力し、ino を終了