From a2cf308294ef707fdc40f96752be641b0422ec6c Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Tue, 14 Apr 2015 02:53:47 +0200 Subject: create semaphore array with random key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- src/semaphore.c | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/semaphore.c diff --git a/src/semaphore.c b/src/semaphore.c new file mode 100644 index 0000000..5447c82 --- /dev/null +++ b/src/semaphore.c @@ -0,0 +1,58 @@ +#include +#include +#include +#include + +#include +#include + + +#ifdef _SEM_SEMUN_UNDEFINED +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; +#endif + + +char *argv0; + + +int main(int argc, char *argv[]) +{ + key_t key; + int id = -1; + + (void) argc; + argv0 = *argv; + + srand(time(NULL)); + for (;;) { + double r = (double)rand(); + r /= (double)RAND_MAX + 1; + r *= (1 << (8 * sizeof(key_t) - 2)) - 1; + key = (key_t)r + 1; + if (key == IPC_PRIVATE) + continue; + id = semget(key, 3, IPC_CREAT | IPC_EXCL | 0600); + if (id != -1) + break; + if ((errno != EEXIST) && (errno != EINTR)) + goto fail; + } + + printf("key:%zx, id:%i\n", (size_t)key, id); + + if (semctl(id, 0, IPC_RMID) == -1) + goto fail; + + return 0; + +fail: + perror(argv0); + if ((id != -1) && (semctl(id, 0, IPC_RMID) == -1)) + perror(argv0); + return 1; +} + -- cgit v1.2.3-70-g09d2