LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1648|回复: 11

关于creat函数的

[复制链接]
发表于 2004-2-3 21:00:16 | 显示全部楼层 |阅读模式

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include "ourhdr.h"

  5. int
  6. main(void)
  7. {
  8.         int fd;
  9.         if((fd=creat("tempfile",FILE_MODE )<0))
  10.               err_sys("creat error");

  11.         if(open("tempfile", O_RDWR)<0)
  12.               err_sys("open error");
  13.        
  14.         if( unlink("tempfile")<0)
  15.               err_sys("unlink error");
  16.        
  17.         printf("file unlinked\n");
  18.         sleep(15);
  19.         printf("done\n");
  20.        
  21.         exit(0);
  22. }
复制代码

是APUE里的一段code,被我加了个creat之后出问题了
编译能通过,但是我执行后,用ls -l tempfile的时候,说没有这个文件
意思就是我的cret没有起作用,但是系统也不说open error,
就直接说file unlinked,晕~~
希望看过这本书的大哥帮帮忙,谢谢!~!!
发表于 2004-2-3 21:05:07 | 显示全部楼层
文件create 后接着被unlink 了,当然会找不到。
 楼主| 发表于 2004-2-3 21:36:57 | 显示全部楼层
不是这样原因,按steven的意思,能清楚的看到文件的变化
发表于 2004-2-3 21:52:50 | 显示全部楼层
程序有问题。
make: Nothing to be done for `create.a.c'.

  1.         int fd;
  2.         if(creat("tempfile",FILE_MODE)<0)
  3.               err_sys("creat error");

  4.         if((fd=open("tempfile", O_RDWR))<0)
  5.               err_sys("open error");
  6.         close(fd);
  7.         if( unlink("tempfile")<0)
  8.               err_sys("unlink error");

  9.         printf("file unlinked\n");
  10.         sleep(15);
  11.         printf("done\n");

  12.         exit(0);
复制代码

open要返回一个文件描述符,creat()那里可以不需要,unlink之前要先关闭文件。

整个程序打印file unlinked  AND  done ,没有其它的看的出的变化呀??
我也看着你的书,你说的是在哪一页?
 楼主| 发表于 2004-2-3 22:09:11 | 显示全部楼层
page:97
我在原来的程序里加了creat,不然执行老大的程序,要自己touch一个
发表于 2004-2-3 22:16:56 | 显示全部楼层
P97没有你的程序?我是看中文版的,直接给出程序名!!
 楼主| 发表于 2004-2-3 23:29:39 | 显示全部楼层
4.15里的unlink
发表于 2004-2-3 23:51:20 | 显示全部楼层
奇怪,在linux试ls -l tempfile 没有,在sleep (15) 时试???

但有个疑问,文件没有close,怎么能删去??
发表于 2004-2-4 00:19:07 | 显示全部楼层

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include "ourhdr.h"

  5. int
  6. main(void)
  7. {
  8.         int fd;
  9.         if((fd=creat("tempfile",FILE_MODE )<0))
  10.               err_sys("creat error");

  11.         if(open("tempfile", O_RDWR)<0)
  12.               err_sys("open error");
  13.                                         < -----加个getchar()
  14.         if( unlink("tempfile")<0)
  15.               err_sys("unlink error");
  16.        
  17.         printf("file unlinked\n");
  18.         sleep(15);
  19.         printf("done\n");
  20.        
  21.         exit(0);
  22. }

复制代码

然后你看看你的文件是否创建了
发表于 2004-2-4 00:36:31 | 显示全部楼层
喂,楼顶的老大
你英文版的后面说明看下去了没?
file unlink后面那个是什么
ls -l tempfile
tempfile not found
这不就和你一样了吗?
stevens的说明是用open或者create创建一个临时文件,然后用unlink删除

我个人理解 open打开tempfile后,马上unlink
内核是知道了,但是没有马上做(你能从书上的结果看到)
文件是删除了(没找到),但是空间还是没放出来
然后15秒后exit了,空间放出来了

我没看过apue不知道对不对
另外还有没明白unlink用处,不知道会不会产生误解
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表