关于一个备份功能的小程序的问题
本帖最后由 jerrymy 于 2011-05-01 14:24 编辑
源码:
- #include<stdio.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<unistd.h>
- #include<fcntl.h>
- int main(int argc,char *argv[])
- {
- int fd;
- int stat,pid;
- struct stat stbuf;
- time_t old_time = 0;
- if( (fd=open(argv[1],O_WRONLY))==-1 )
- {
- printf("can't ooen watchfile\n");
- return 2;
- }
- fstat(fd,&stbuf);
- old_time = stbuf.st_mtime;
- for(;;)
- {
- fstat(fd,&stbuf);
- if(old_time != stbuf.st_mtime)
- {
- while(pid = vfork()== -1 );
- if(pid == 0)
- {
- execl("/bin/cp","/bin/cp",argv[1],argv[2],0);
- return 3;
- }
- wait(&stat);
- old_time = stbuf.st_mtime;
- }
- else
- sleep(20);
- }
- }
复制代码程序的功能:循环检测原文件的mtime,如果mtime改变则在子程序执行备份。
这是一个群里的朋友问的,这个程序在我的Cent OS5.6上能执行,但有个诡异的现象:创建的原文件必须是空文件/
并且只有用touch flie 才能执行备份。
如果用编辑器更改原文件的mtime则程序永远都在无限循环,不会执行备份。
但我加了一句之后变为下面,即在for循环里加上fd=open(argv[1],O_WRONLY);这句:
- #include<stdio.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<unistd.h>
- #include<fcntl.h>
- int main(int argc,char *argv[])
- {
- int fd;
- int stat,pid;
- struct stat stbuf;
- time_t old_time = 0;
- if( (fd=open(argv[1],O_WRONLY))==-1 )
- {
- printf("can't ooen watchfile\n");
- return 2;
- }
- fstat(fd,&stbuf);
- old_time = stbuf.st_mtime;
- for(;;)
- {
- fd=open(argv[1],O_WRONLY);
- fstat(fd,&stbuf);
- if(old_time != stbuf.st_mtime)
- {
- while(pid = vfork()== -1 );
- if(pid == 0)
- {
- execl("/bin/cp","/bin/cp",argv[1],argv[2],0);
- return 3;
- }
- wait(&stat);
- old_time = stbuf.st_mtime;
- }
- else
- sleep(20);
- }
- }
复制代码更改后的程序用touch和编辑器编辑之后都能执行备份。我觉得很纳闷,烦劳前辈们解释一下/
循环前面的open打开的fd跟循环的open打开的fd的stat结构体有什么不一样。
另外为什么成功执行备份后都程序都会退出,但从源码来看,程序的意图是无限循环,一旦文件mtime改变就执行备份,but。。。。
这是清华大学某某某写的一本linux 编程书籍上的例子。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
目的是根据文件修改时间的变化来备份文件。
只要mtime更改了就copy.
程序虽然看起来有点点长,但功能很简单,请路过的认真看一下。![](https://www.wenjiangs.com/wp-content/uploads/chinaunix/202207/emn10.gif)
复制代码[/code]
回复 3# snriyt
你发的什么啊,没东西啊。
回复 4# jerrymy
代码括起来吧
顶一下。
估计原来程序“如果用编辑器更改原文件的mtime则程序永远都在无限循环,不会执行备份”是由于系统对打开文件属性(*fd)的缓存,使得每次fstat(fd,&stbuf)内容不变。
更新的代码中没有fclose(),运行时间长了会出问题。
本帖最后由 jerrymy 于 2011-05-03 11:33 编辑
回复 7# yug1129
第一点有同感,但不确定。
加入那个语句仅仅是希望程序能执行成功。
即便是执行成功的情形,程序的行为跟作者的本意也不一致,执行一次之后父进程也嗝屁了,所以都不用fclose()了![](https://www.wenjiangs.com/wp-content/uploads/chinaunix/202207/icon_eek.gif)
如果程序按照预期的执行,fclose()是必要的。
为什么不直接使用system()?为什么要vfork()?是为了检验系统调用还是为了实现备份功能?