Practical 7. Program for detection of single node failure in a network. - SCIENCE BUZZ

Practical 7. Program for detection of single node failure in a network.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#define NUM_NODES 5
#define HEARTBEAT_INTERVAL 2
#define TIMEOUT 4

typedef struct Node {
    int id;
    bool alive;
    pthread_t thread;
} Node;

void* sendHeartbeat(void* arg) {
    Node* node = (Node*)arg;
    while (1) {
        sleep(HEARTBEAT_INTERVAL);
        node->alive = true;
        printf("Node %d: Sending heartbeat\n", node->id);
    }
    return NULL;
}

void* monitorNodes(void* arg) {
    Node* nodes = (Node*)arg;
    while (1) {
        sleep(TIMEOUT);
        for (int i = 0; i < NUM_NODES; i++) {
            if (!nodes[i].alive) {
                printf("Node %d: Failed\n", nodes[i].id);
            }
            nodes[i].alive = false;
        }
    }
    return NULL;
}

int main() {
    Node nodes[NUM_NODES];

    for (int i = 0; i < NUM_NODES; i++) {
        nodes[i].id = i + 1;
        nodes[i].alive = false;
        pthread_create(&nodes[i].thread, NULL, sendHeartbeat, &nodes[i]);
    }

    pthread_t monitorThread;
    pthread_create(&monitorThread, NULL, monitorNodes, nodes);

    for (int i = 0; i < NUM_NODES; i++) {
        pthread_join(nodes[i].thread, NULL);
    }
    pthread_join(monitorThread, NULL);

    return 0;
}



Practical 7. Program for detection of single node failure in a network. Practical 7. Program for detection of single node failure in a network. Reviewed by RISHI and ARYAN on 22:54 Rating: 5

No comments:

May I help you ?

Powered by Blogger.