summaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c41
1 files changed, 16 insertions, 25 deletions
diff --git a/src/utils.c b/src/utils.c
index deb36f8..a223462 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -249,49 +249,40 @@ char *shell_path_expand(const char *path)
#define MAX_TRY 10
-struct Lock *device_lock(const char *path)
+int device_lock(const char *path)
{
- struct Lock *result = (struct Lock*)calloc(1, sizeof(struct Lock));
- if (result == NULL) {
+ char *lock_path;
+ if (asprintf(&lock_path, "/var/lock/LCK..%s", basename(path)) < 0) {
log_error("out of memory");
- return device_unlock(result);
- }
-
- if (asprintf(&result->path, "/var/lock/LCK..%s", basename(path)) < 0) {
- log_error("out of memory");
- return device_unlock(result);
+ return -1;
}
- result->fd = open(result->path, O_CREAT | O_RDWR, 0644);
- if (result->fd >= 0) {
+ int lock_fd = open(lock_path, O_CREAT | O_RDWR, 0644);
+ if (lock_fd >= 0) {
unsigned char num_try = 0;
while (1) {
- int lockErr = flock(result->fd, LOCK_EX | LOCK_NB);
+ int lockErr = flock(lock_fd, LOCK_EX | LOCK_NB);
if (lockErr == 0) {
- return result;
+ free(lock_path);
+ return lock_fd;
} else if (errno != EWOULDBLOCK) {
break;
}
if (num_try++>=MAX_TRY) {
- //something locks device too long
- break;
+ break; //something locks device too long
}
usleep(100000ul);//100ms
}
- log_error("failed to create %s: %m", result->path);
+ log_error("failed to create %s: %m", lock_path);
}
- return device_unlock(result);
+ free(lock_path);
+ return device_unlock(lock_fd);
}
-struct Lock *device_unlock(struct Lock *lock)
+int device_unlock(int lock)
{
- if (lock) {
- close(lock->fd);
- free(lock->path);
- lock->path = NULL;
- free(lock);
- }
- return NULL;
+ close(lock);
+ return -1;
}
int indexOfChar(const char *array, int len, char character)