C语言中Linux下锁定文件与解锁文件问题i无效
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h> /*包含头文件。*/
main()
{
int fd,i; /*定义变量。*/
char path[]="/root/txt1.txt"; /*要访问的文件。*/
extern int errno; /*定义错误号。*/
fd=open(path,O_WRONLY|O_CREAT); /*打开文件。*/
if(fd!=-1) /*打开成功。*/
{
printf("opened file %s .\n",path);
printf("please input a number to lock the file.\n"); /*输入一个数字。*/
scanf("%d",&i); /*输入。*/
if(flock(fd,LOCK_EX)==0) /*锁定文件。*/
{
printf("the file was locked.\n"); /*输出信息。*/
}
else
{
printf("the file was not locked.\n"); /*文件锁定失败。*/
}
printf("please input a number to unlock the file.\n"); /*提示输入。*/
scanf("%d",&i); /*输入。*/
if(flock(fd,LOCK_UN)==0) /*解除文件锁定。*/
{
printf("the file was unlocked.\n"); /*输出解除锁定成功。*/
}
else
{
printf("the file was not unlocked.\n"); /*输出解除锁定失败。*/
}
close(fd); /*关闭文件。*/
}
else
{
printf("cant't open file %s.\n",path); /*不能打开文件的情况。*/
printf("errno:%d\n",errno); /*显示错误号。*/
printf("ERR :%s\n",strerror(errno)); /*显示错误信息。*/
}
}
运行环境ubuntu11.04自代GCC
[解决办法]
http://linux.die.net/
http://www.cplusplus.com/
[解决办法]
不太明白楼主想问什么
i的值,输入多少没关系,它主要起个暂停的作用,随便输入个数让程序继续往下跑。
代码本身就是先锁定,然后等你按任意数字键后再解锁