一、常用函数
#include <stdio.h>
int main(){
char c;
FILE *pin, *pout;
//open file
pin = fopen("file.in", "r");
pout = fopen("file.out", "w+");
while(c = fgetc(pin) != EOF){
fputc(c, pout);
}
fclose(pin);
fclose(pout);
return 0;
}
二、文件锁定
struct file_lock {
struct file_lock *fl_next; /* singly linked list for this inode */
struct list_head fl_link; /* doubly linked list of all locks */
struct list_head fl_block; /* circular list of blocked processes */
fl_owner_t fl_owner;
unsigned char fl_flags;
unsigned char fl_type;
unsigned int fl_pid;
struct pid *fl_nspid;
wait_queue_head_t fl_wait;
struct file *fl_file;
loff_t fl_start;
loff_t fl_end;
struct fasync_struct * fl_fasync; /* for lease break notifications */
unsigned long fl_break_time; /* for nonblocking lease breaks */
const struct file_lock_operations *fl_ops; /* Callbacks for filesystems */
const struct lock_manager_operations *fl_lmops; /* Callbacks for lockmanagers */
union {
struct nfs_lock_info nfs_fl;
struct nfs4_lock_info nfs4_fl;
struct {
struct list_head link; /* link in AFS vnode's pending_locks list */
int state; /* state of grant or error if -ve */
} afs;
} fl_u;
};
在Linux中有强制锁和建议锁两种锁,强制锁由系统内核空间支持(和内核操作相关的函数都会判断),建议锁其实就是一个标识锁由用户空间支持(手动判断)。
...
short l_type; /* Type of lock: F_RDLCK(共享锁),
F_WRLCK(独占锁), F_UNLCK (删除锁)*/
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock (起点)*/
off_t l_len; /* Number of bytes to lock(长度) */
pid_t l_pid; /* PID of process blocking our lock
(F_GETLK only)(拥有锁的进程ID号) */
...
};
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
//open file
int fd = open("hello", O_RDWRIO_CREAT, 0666);
if(fd > 0){
//lock file
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = getpid();
int rd = fcntl(fd, F_SETLK, &lock);
printf("return value of lock:%d\n", rd);
while(1){
rd++;
}
}
return 0;
}
三、错误处理
系统级调用函数失败之后会设置外部变量error的值来指明失败原因。然后可以使用perror将最新的error输出。#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd = open("helloworld", O_RDONL, 0666);
if(fd < 0){
perror("open error");
}
return 0;
}