#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中有强制锁和建议锁两种锁,强制锁由系统内核空间支持(和内核操作相关的函数都会判断),建议锁其实就是一个标识锁由用户空间支持(手动判断)。#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;
}#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;
}原文:http://blog.csdn.net/dawanganban/article/details/38828957