summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/utils.c41
-rw-r--r--src/utils.h9
2 files changed, 18 insertions, 32 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)
diff --git a/src/utils.h b/src/utils.h
index eb9d5bc..62d76f1 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -30,18 +30,13 @@ enum {
USER_YESNO_YES = 1,
};
-struct Lock {
- char *path;
- int fd;
-};
-
int user_yesno(int def, const char *fmt, ...);
int systemf(const char *fmt, ...);
FILE *popenf(const char *mode, const char *fmt, ...);
char *shell_path_expand(const char *path);
-struct Lock *device_lock(const char *path);
-struct Lock *device_unlock(struct Lock *lock);
+int device_lock(const char *path);
+int device_unlock(int lock);
int indexOfChar(const char *array, int len, char character);