Last active
August 29, 2015 13:57
-
-
Save yuikns/9561101 to your computer and use it in GitHub Desktop.
windows , lock a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <windows.h> | |
int main() | |
{ | |
//获取进程ID,因为你希望是多个进程运行同时写一个文件,所以,我们打印出进程ID | |
DWORD dwProcessID = GetCurrentProcessId(); | |
//初始化我们要写入文件中的内容,及该内容长度; | |
//为了让每次写入内容变化,此处只声明,需要时候再写。 | |
char szContent[100] = {0}; | |
//sprintf(szContent, "process[%u] write file\r\n", dwProcessID); | |
//DWORD dwContentLen = strlen(szContent); | |
int j; | |
DWORD dwContentLen; | |
//创建互斥量,这样可以进行进程间的互斥,当然用这个也可以做线程间的互斥 | |
HANDLE hMutex = CreateMutex(NULL, FALSE, "MyFileMutex"); | |
if(NULL == hMutex) | |
{ | |
printf("[%u]Create/Open Mutex error!\r\n", dwProcessID); | |
return 1; | |
} | |
//创建或打开文件 | |
HANDLE hFile = CreateFile("output.log",//FILE NAME | |
GENERIC_READ | GENERIC_WRITE, | |
FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, | |
OPEN_ALWAYS, | |
FILE_ATTRIBUTE_ARCHIVE, | |
NULL); | |
//创建/打开失败 | |
if(INVALID_HANDLE_VALUE == hFile) | |
{ | |
printf("[%u]Create/Open file error!\r\n", dwProcessID); | |
return -1; | |
} | |
//printf("\n Invalid_handle_value:%d\n hFile:%d\n",INVALID_HANDLE_VALUE,hFile); | |
//循环写入文件 | |
for(int i = 0; i < 10000 ; i++) | |
{ | |
//设置写入内容和长度 | |
//由于它不需要临界资源,所以放在等待临界资源和释放互斥量之外面 | |
j=i%3; | |
sprintf(szContent, "[%d]%d::%d\r\n",3,j,dwProcessID); | |
dwContentLen = strlen(szContent); | |
DWORD len = 0; | |
//等待临界资源,即锁定文件 | |
WaitForSingleObject(hMutex, INFINITE); | |
//获得写入权利 | |
printf("Process[%u] Get the signal\r\n", dwProcessID); | |
//因为是共享写文件,即多个程序写一个文件,所以一定要将文件指针偏移到尾部 | |
SetFilePointer(hFile, 0, NULL, FILE_END); | |
//写入文件 | |
BOOL rnt = WriteFile(hFile, szContent, dwContentLen, &len, NULL); | |
//写入失败 | |
if(rnt == FALSE) | |
{ | |
printf("Process[%u] Fail to write file\r\n", dwProcessID); | |
} | |
//释放互斥量,解除锁定 | |
ReleaseMutex(hMutex); | |
//加个Sleep便于我们中间观察结果 | |
Sleep(30); | |
} | |
CloseHandle(hMutex); | |
CloseHandle(hFile); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment