summaryrefslogtreecommitdiff
path: root/addjob.c
blob: 6af784708d2ab9e43c64e103ecdd37fe777d6bfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "shared.h"

int main(int argc, char *argv[]) {
    if (argc != 2 && argc != 3) {
        fprintf(stderr, "Usage: %s <path-to-job-binary> [node]\n", argv[0]);
        return 1;
    }

    int target_node = -1;
    if (argc == 3) {
        target_node = atoi(argv[2]);
        if (target_node < 0 || target_node >= MAX_NODES) {
            fprintf(stderr, "[addjob] Invalid node ID: %d\n", target_node);
            return 2;
        }
    }

    int shm_fd = shm_open(SHM_NAME, O_RDWR, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        return 1;
    }

    JobQueue *queue = mmap(NULL, sizeof(JobQueue), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (queue == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    pthread_mutex_lock(&queue->mutex);
    if ((queue->tail + 1) % MAX_JOBS == queue->head) {
        printf("[addjob] Queue full\n");
    } else {
        strncpy(queue->jobs[queue->tail], argv[1], MAX_PATH);
        queue->job_nodes[queue->tail] = target_node; 
        queue->tail = (queue->tail + 1) % MAX_JOBS;
        printf("[addjob] Queued job: %s", argv[1]);
        if (target_node != -1)
            printf(" for node %d", target_node);
        printf("\n");
    }
    pthread_mutex_unlock(&queue->mutex);

    munmap(queue, sizeof(JobQueue));
    close(shm_fd);
    return 0;
}