summaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
authorJeff Hatch <jhatch@multitech.com>2020-04-13 14:40:47 -0500
committerJeff Hatch <jhatch@multitech.com>2020-04-13 14:40:47 -0500
commit8ce0f4a320f56b582e51cca09ebf8fbc8326987d (patch)
treecf6d684596ddeb198f221b9eaad69ca307e503f4 /src/utils.c
parent3d3c735f3bbd269f97bd59a246d5f18b010eda2b (diff)
parentd48fa68d6207b25061d5276021b1dd25ce5da89d (diff)
downloadsms-utils-8ce0f4a320f56b582e51cca09ebf8fbc8326987d.tar.gz
sms-utils-8ce0f4a320f56b582e51cca09ebf8fbc8326987d.tar.bz2
sms-utils-8ce0f4a320f56b582e51cca09ebf8fbc8326987d.zip
Merge branch 'MTX-3262-single-instance-guard' into 'master'
Mtx 3262 single instance guard See merge request !3
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c72
1 files changed, 39 insertions, 33 deletions
diff --git a/src/utils.c b/src/utils.c
index b93634c..e7d6b69 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -33,6 +33,7 @@
#include <fcntl.h>
#include <string.h>
#include <linux/limits.h>
+#include <sys/file.h>
#include "utils.h"
#include "log.h"
@@ -248,44 +249,49 @@ char *shell_path_expand(const char *path)
#define MAX_TRY 10
-char *device_lock(const char *path)
+struct Lock *device_lock(const char *path)
{
- int tmp;
- char *name = basename(path);
- int fd;
- char str[32];
- char *lock;
- unsigned char num_try=0;
-
- tmp = asprintf(&lock, "/var/lock/LCK..%s", name);
- if (tmp < 0) {
+ struct Lock *result = (struct Lock*)calloc(1, sizeof(struct Lock));
+ if (result == NULL) {
log_error("out of memory");
return NULL;
}
- do{
- fd = open(lock, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0644);
- if (fd > 0) {
- break;
- }else{
- log_error("%i number of trying to create %s: %m",num_try+1,lock);
- };
- if(num_try++>=MAX_TRY){
- //something locks device too long
- log_error("failed to create %s: %m", lock);
- free(lock);
- return NULL;
- }
- usleep(100000ul);//100ms
- }while(1);
-
- snprintf(str, sizeof(str), "%10d\n", getpid());
-
- full_write(fd, str, strlen(str));
-
- close(fd);
-
- return lock;
+ if (asprintf(&result->path, "/var/lock/LCK..%s", basename(path)) < 0) {
+ log_error("out of memory");
+ return NULL;
+ }
+
+ result->fd = open(result->path, O_CREAT | O_RDWR, 0644);
+ if (result->fd >= 0) {
+ unsigned char num_try = 0;
+ while (1) {
+ int lockErr = flock(result->fd, LOCK_EX | LOCK_NB);
+ if (lockErr == 0) {
+ return result;
+ } else if (errno != EWOULDBLOCK) {
+ break;
+ }
+ if (num_try++>=MAX_TRY) {
+ //something locks device too long
+ break;
+ }
+ usleep(100000ul);//100ms
+ }
+ log_error("failed to create %s: %m", result->path);
+ device_unlock(result);
+ }
+ return NULL;
+}
+
+struct Lock *device_unlock(struct Lock *lock)
+{
+ if (lock) {
+ close(lock->fd);
+ free(lock->path);
+ free(lock);
+ }
+ return NULL;
}
int indexOfChar(const char *array, int len, char character)