Skip to content

Instantly share code, notes, and snippets.

@harryhare
Created November 8, 2018 04:13
Show Gist options
  • Save harryhare/ccd5cd8121ebff007ac43ca5fc402b7a to your computer and use it in GitHub Desktop.
Save harryhare/ccd5cd8121ebff007ac43ca5fc402b7a to your computer and use it in GitHub Desktop.
use fcntl to lock file interactively
#include <iostream>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <errno.h>
#include "util.h"
#include <vector>
using namespace std;
int GetDirFiles(const std::string &dir, std::vector<std::string> *result) {
int res = 0;
result->clear();
DIR *d = opendir(dir.c_str());
if (d == NULL) {
return errno;
}
struct dirent *entry;
while ((entry = readdir(d)) != NULL) {
if (strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) {
continue;
}
result->push_back(entry->d_name);
}
closedir(d);
return res;
}
int GetFileLength(const std::string &file) {
struct stat stat_buf;
int rc = stat(file.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
int FileAppend(int fd, const std::string &value) {
if (fd < 0) {
return -1;
}
size_t value_len = value.size();
const char *pos = value.data();
while (value_len > 0) {
ssize_t r = write(fd, pos, value_len);
if (r < 0) {
if (errno == EINTR) {
continue; // Retry
}
return -1;
}
pos += r;
value_len -= r;
}
return 0;
}
bool FileExists(const std::string &path) {
return access(path.c_str(), F_OK) == 0;
}
void test() {
const string file_name = "/Users/unity/git/engine/Makefile";
int return_code = 0;
vector<string> result;
GetDirFiles("/", &result);
for (auto x:result) {
cout << x << endl;
}
int l = GetFileLength(file_name);
cout << l << endl;
return_code = access(file_name.c_str(), F_OK | R_OK | W_OK);
cout << return_code << endl;
}
void prompt(string msg) {
cout << msg << endl;
getchar();
}
void checkrc(int rc, string err_msg) {
if (rc < 0) {
cerr << "code:" << rc << endl;
cerr << "when: " << err_msg << endl;
perror("error");
exit(-1);
}
}
int main() {
int fd = open("test5.txt", O_CREAT|O_RDWR,0666);
int rc;
checkrc(fd, "cannot open file");
prompt("press enter to set lock");
struct flock f;
memset(&f, 0, sizeof(f));
f.l_type = F_WRLCK;
f.l_whence = SEEK_SET;
rc = fcntl(fd, F_SETLK, &f);
checkrc(rc, "set lock");
prompt("press enter to unlock");
f.l_type = F_UNLCK;
rc = fcntl(fd, F_UNLCK, &f);
prompt("press enter to exit");
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment