提交 5bcf051a 编写于 作者: L LinJiawei

lock-emu.c: write lock holder's name into lock file

上级 59330107
......@@ -3,13 +3,17 @@
#include<stdlib.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#define BUF_SIZE 32
int tryLock(char * file){
return open(file, O_CREAT | O_EXCL);
return open(file, O_CREAT | O_EXCL | O_WRONLY, 0666);
}
int main(int argc, char* argv[]){
int fd;
char user[BUF_SIZE];
if(argc < 2){
printf("arguments are not right!\n");
exit(-1);
......@@ -17,10 +21,20 @@ int main(int argc, char* argv[]){
do{
fd = tryLock(argv[1]);
if(fd > 0) break;
printf("there is a job running, waiting ...\n");
sleep(10);
} while(1);
if(fd > 0){
getlogin_r(user, BUF_SIZE);
write(fd, user, strlen(user));
break;
} else {
// someone is holding the lock...
fd = open(argv[1], O_RDONLY);
if(fd > 0){
read(fd, user, BUF_SIZE);
printf("%s is holding the lock, waiting ...\n", user);
}
}
sleep(10);
} while(1);
return 0;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册