Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Task 1: Message Queue Between Two Unrelated Processes Scenario: You are building a chat…

  1. User

    Task 1: Message Queue Between Two Unrelated Processes Scenario: You are building a chat system that allows communication between two unrelated processes. One process is responsible for sending messages, and the other is responsible for receiving them.

    1. Create two programs, sender.c and receiver.c.
    2. The sender program should continuously take input from the user (a string) and write it into a FIFO pipe.
    3. The receiver program should read the messages from the FIFO pipe and display them on the screen.
    4. Ensure proper synchronization between the sender and receiver programs using the named pipe.

    Task 2: Real-Time Logging System Scenario: Your system requires a real-time logging system where a process continuously logs system status to a FIFO pipe, and another process reads the log and stores it in a log file (log.txt).

    1. The logger process should generate random system status messages every 5 seconds and write them into the FIFO.
    2. The log reader process should read the logs from the FIFO and append them to log.txt.
    3. Make sure the FIFO is read and written to continuously without any data loss.

    Task 3: Client-Server Calculation System Scenario: You are tasked with implementing a simple client-server system using FIFO pipes. The client will send mathematical expressions to the server, and the server will evaluate the expression and return the result to the client.

    1. The client process should take a simple mathematical expression as input (e.g., 5 + 3) and send it through a FIFO pipe to the server.

    2. The server process should read the expression, evaluate it, and return the result through another FIFO pipe to the client.

    3. The client should display the result once it is received.

    4. Ensure both processes handle multiple requests and responses properly.

    Task 4: Temperature Monitoring System with Multiple Sensors Scenario: You are implementing a temperature monitoring system where three independent sensor processes report temperature data to a central monitor process via FIFO pipes.

    1. Create three sensor programs (sensor1.c, sensor2.c, sensor3.c). Each sensor should simulate reading a temperature value (a random number between 20°C and 30°C) and write this value into its own FIFO pipe every 3 seconds.
    2. The central monitor process should read the values from all three FIFO pipes and display the temperatures from each sensor in real-time.
    3. Ensure that the monitor can handle the incoming data simultaneously from all sensors.

    Note: For all tasks, remember to:

    • Create the FIFO pipes using the mkfifo() function.
    • Use appropriate read and write functions (read(), write()) to transfer data between the processes.
    • Handle pipe creation, opening, and closing carefully to avoid deadlocks or resource leaks.
    • Use unlink() to remove the FIFO pipes after completing each program.
  2. Assistant

    Sure! Below are detailed solutions for each of the four tasks you've outlined. Each task involves inter-process communication using FIFO (named pipes) in C. I'll provide explanations, C code for each program involved, and instructions on how to compile and run them.


    Task 1: Message Queue Between Two Unrelated Processes

    Scenario Recap

    • Sender (sender.c): Continuously takes user input and writes it to a FIFO pipe.
    • Receiver (receiver.c): Reads messages from the FIFO pipe and displays them.
    • Synchronization: Ensure proper synchronization using the named pipe.

    Solution Overview

    1. Create a Named Pipe (FIFO): We'll use mkfifo() to create a FIFO named pipe.
    2. Sender Process: Opens the FIFO for writing, takes user input in a loop, and writes it to the FIFO.
    3. Receiver Process: Opens the FIFO for reading and continuously reads messages from it, displaying them on the screen.
    4. Clean Up: After the processes are terminated, unlink (remove) the FIFO using unlink().

    Implementation

    1. Defining the FIFO Path

    Let's define a common FIFO path that both programs will use. For this example, we'll name it myfifo.

    // common.h
    #ifndef COMMON_H
    #define COMMON_H
    
    #define FIFO_PATH "myfifo"
    
    #endif
    

    You can create a separate header file (e.g., common.h) to share constants between programs.

    2. Sender Program (sender.c)

    // sender.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For write and close
    #include "common.h"
    
    #define BUFFER_SIZE 1024
    
    int main() {
        // Create the FIFO if it does not exist
        if (mkfifo(FIFO_PATH, 0666) == -1) {
            perror("mkfifo");
            // It's okay if the FIFO already exists
        }
    
        // Open the FIFO for writing
        int fd = open(FIFO_PATH, O_WRONLY);
        if (fd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
    
        char buffer[BUFFER_SIZE];
        printf("Sender: Type messages to send. Type 'exit' to quit.\n");
    
        while (1) {
            // Get user input
            printf("You: ");
            if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
                perror("fgets");
                break;
            }
    
            // Remove newline character
            buffer[strcspn(buffer, "\n")] = '\0';
    
            // Check for exit condition
            if (strcmp(buffer, "exit") == 0) {
                break;
            }
    
            // Write the message to FIFO
            if (write(fd, buffer, strlen(buffer) + 1) == -1) {
                perror("write");
                break;
            }
        }
    
        // Close the FIFO
        close(fd);
    
        // Unlink (remove) the FIFO
        unlink(FIFO_PATH);
    
        return 0;
    }
    

    3. Receiver Program (receiver.c)

    // receiver.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For read and close
    #include <string.h>
    #include "common.h"
    
    #define BUFFER_SIZE 1024
    
    int main() {
        // Create the FIFO if it does not exist
        if (mkfifo(FIFO_PATH, 0666) == -1) {
            perror("mkfifo");
            // It's okay if the FIFO already exists
        }
    
        // Open the FIFO for reading
        int fd = open(FIFO_PATH, O_RDONLY);
        if (fd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
    
        char buffer[BUFFER_SIZE];
        printf("Receiver: Waiting for messages...\n");
    
        while (1) {
            // Read from FIFO
            ssize_t bytesRead = read(fd, buffer, BUFFER_SIZE);
            if (bytesRead > 0) {
                printf("Received: %s\n", buffer);
                // Optionally, handle exit condition if needed
                if (strcmp(buffer, "exit") == 0) {
                    printf("Receiver: Exit command received. Exiting.\n");
                    break;
                }
            } else if (bytesRead == 0) {
                // End of file (writer has closed the FIFO)
                printf("Receiver: Writer closed the FIFO. Exiting.\n");
                break;
            } else {
                perror("read");
                break;
            }
        }
    
        // Close the FIFO
        close(fd);
    
        // Unlink (remove) the FIFO
        unlink(FIFO_PATH);
    
        return 0;
    }
    

    4. Compilation Instructions

    Use gcc to compile both programs.

    gcc -o sender sender.c
    gcc -o receiver receiver.c
    

    5. Running the Programs

    1. Start the Receiver: Open a terminal and run the receiver program first.

      ./receiver
      

      Output:

      Receiver: Waiting for messages...
      
    2. Start the Sender: Open another terminal and run the sender program.

      ./sender
      

      Output:

      Sender: Type messages to send. Type 'exit' to quit.
      You:
      
    3. Send Messages: Type messages in the sender terminal. They will appear in the receiver terminal.

      Example:

      • Sender Terminal:

        You: Hello, Receiver!
        You: How are you?
        You: exit
        
      • Receiver Terminal:

        Received: Hello, Receiver!
        Received: How are you?
        Received: exit
        Receiver: Exit command received. Exiting.
        
    4. Cleanup: Both programs will unlink (remove) the FIFO upon exiting. Ensure both programs have terminated to clean up properly.

    Notes on Synchronization

    • Blocking Nature of FIFO: When the receiver opens the FIFO for reading, it blocks until a writer (sender) opens it for writing, and vice versa. This behavior ensures synchronization between the two processes.
    • Handling Multiple Messages: The sender and receiver run in loops, allowing continuous communication without data loss as long as both are running.
    • Graceful Termination: Using an "exit" command allows both processes to terminate gracefully, ensuring the FIFO is properly unlinked.

    Task 2: Real-Time Logging System

    Scenario Recap

    • Logger Process: Generates random system status messages every 5 seconds and writes them to a FIFO.
    • Log Reader Process: Reads logs from the FIFO and appends them to log.txt.
    • Continuous Operation: Ensure no data loss and continuous read/write.

    Solution Overview

    1. Create a Named Pipe (FIFO): We'll use mkfifo() to create a FIFO named pipe (e.g., logfifo).
    2. Logger Process (logger.c): Generates random status messages at 5-second intervals and writes them to the FIFO.
    3. Log Reader Process (log_reader.c): Continuously reads messages from the FIFO and appends them to log.txt.
    4. Clean Up: Remove the FIFO after termination.

    Implementation

    1. Logger Process (logger.c)

    // logger.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For write, close, unlink, sleep
    #include <time.h>
    #include "common.h"
    
    #define FIFO_PATH "logfifo"
    #define BUFFER_SIZE 256
    
    const char* generate_status_message() {
        // Sample status messages
        const char* statuses[] = {
            "System running smoothly.",
            "CPU usage at 30%.",
            "Memory usage at 45%.",
            "Disk space available: 120GB.",
            "Network latency is low.",
            "No errors detected.",
            "Service X started successfully.",
            "Scheduled backup completed.",
            "User login detected.",
            "Security scan passed."
        };
        int num_statuses = sizeof(statuses) / sizeof(statuses[0]);
        return statuses[rand() % num_statuses];
    }
    
    int main() {
        srand(time(NULL)); // Initialize random number generator
    
        // Create the FIFO if it does not exist
        if (mkfifo(FIFO_PATH, 0666) == -1) {
            perror("mkfifo");
            // It's okay if the FIFO already exists
        }
    
        // Open the FIFO for writing. Open in non-blocking mode to avoid blocking if no reader.
        int fd = open(FIFO_PATH, O_WRONLY);
        if (fd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
    
        while (1) {
            // Generate a random status message
            const char* message = generate_status_message();
    
            // Get current time
            time_t now = time(NULL);
            struct tm* tm_info = localtime(&now);
            char time_str[26];
            strftime(time_str, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    
            // Prepare the log entry
            char log_entry[BUFFER_SIZE];
            snprintf(log_entry, BUFFER_SIZE, "[%s] %s\n", time_str, message);
    
            // Write the log entry to FIFO
            if (write(fd, log_entry, strlen(log_entry) + 1) == -1) {
                perror("write");
                // Optionally, exit or continue based on the error
                break;
            }
    
            printf("Logger: Logged message: %s", log_entry);
    
            // Sleep for 5 seconds
            sleep(5);
        }
    
        // Close the FIFO
        close(fd);
    
        // Unlink (remove) the FIFO
        unlink(FIFO_PATH);
    
        return 0;
    }
    

    2. Log Reader Process (log_reader.c)

    // log_reader.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For read, close, unlink
    #include <string.h>
    #include "common.h"
    
    #define FIFO_PATH "logfifo"
    #define BUFFER_SIZE 256
    #define LOG_FILE "log.txt"
    
    int main() {
        // Create the FIFO if it does not exist
        if (mkfifo(FIFO_PATH, 0666) == -1) {
            perror("mkfifo");
            // It's okay if the FIFO already exists
        }
    
        // Open the FIFO for reading
        int fd = open(FIFO_PATH, O_RDONLY);
        if (fd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
    
        // Open the log file for appending
        FILE* log_file = fopen(LOG_FILE, "a");
        if (log_file == NULL) {
            perror("fopen");
            close(fd);
            exit(EXIT_FAILURE);
        }
    
        char buffer[BUFFER_SIZE];
        printf("Log Reader: Listening for log messages...\n");
    
        while (1) {
            // Read from FIFO
            ssize_t bytesRead = read(fd, buffer, BUFFER_SIZE);
            if (bytesRead > 0) {
                // Append to log file
                fprintf(log_file, "%s", buffer);
                fflush(log_file); // Ensure it's written to disk
    
                printf("Log Reader: Appended to log.txt: %s", buffer);
            } else if (bytesRead == 0) {
                // End of file (writer has closed the FIFO)
                printf("Log Reader: Logger closed the FIFO. Exiting.\n");
                break;
            } else {
                perror("read");
                break;
            }
        }
    
        // Close file descriptors
        fclose(log_file);
        close(fd);
    
        // Unlink (remove) the FIFO
        unlink(FIFO_PATH);
    
        return 0;
    }
    

    3. Compilation Instructions

    Use gcc to compile both programs.

    gcc -o logger logger.c
    gcc -o log_reader log_reader.c
    

    4. Running the Programs

    1. Start the Log Reader: Open a terminal and run the log reader program first.

      ./log_reader
      

      Output:

      Log Reader: Listening for log messages...
      
    2. Start the Logger: Open another terminal and run the logger program.

      ./logger
      

      Output:

      Logger: Logged message: [2023-10-10 12:00:00] System running smoothly.
      Logger: Logged message: [2023-10-10 12:00:05] CPU usage at 30%.
      ...
      
    3. Check log.txt: The log_reader appends messages to log.txt. You can monitor it using tail -f log.txt in another terminal.

      tail -f log.txt
      

      Output:

      [2023-10-10 12:00:00] System running smoothly.
      [2023-10-10 12:00:05] CPU usage at 30%.
      ...
      
    4. Termination: To terminate the processes, you can use Ctrl+C in their respective terminals. Ensure that both processes terminate to clean up the FIFO properly.

    Notes on Ensuring No Data Loss

    • Blocking Nature: If the logger writes to the FIFO while no reader is present, it will block until a reader opens the FIFO. This behavior ensures that messages are not lost.
    • Continuous Operation: Both processes run in infinite loops, enabling continuous logging and reading.
    • Error Handling: The programs handle errors gracefully, printing error messages and exiting if critical failures occur.
    • Buffered Writing: The log reader flushes the output to log.txt immediately after writing, ensuring that data is not lost in the event of a crash.

    Task 3: Client-Server Calculation System

    Scenario Recap

    • Client Process: Takes mathematical expressions as input, sends them to the server via FIFO, and receives results through another FIFO.
    • Server Process: Reads expressions from FIFO, evaluates them, and sends back results via another FIFO.
    • Multiple Requests Handling: Ensure proper handling of multiple requests and responses.

    Solution Overview

    1. Create Two Named Pipes (FIFOs):
      • Request FIFO: client_to_server_fifo
      • Response FIFO: server_to_client_fifo
    2. Client Process (client.c):
      • Takes user input (expressions), sends to server via request FIFO.
      • Waits for result from server via response FIFO and displays it.
    3. Server Process (server.c):
      • Continuously reads expressions from request FIFO.
      • Evaluates the expression.
      • Sends the result back via response FIFO.
    4. Handling Multiple Requests:
      • Both FIFOs remain open while the processes are running.
      • Proper synchronization ensures that multiple messages are handled sequentially.
    5. Clean Up: Remove both FIFOs upon termination.

    Security Consideration

    • Expression Evaluation: A simple and safe parser/evaluator is required to prevent code injection. For simplicity, we'll restrict to simple binary operations (addition, subtraction, multiplication, division) with two operands.

    Implementation

    1. Defining FIFO Paths

    Let's define two FIFO paths in a common header.

    // common.h
    #ifndef COMMON_H
    #define COMMON_H
    
    #define REQUEST_FIFO "client_to_server_fifo"
    #define RESPONSE_FIFO "server_to_client_fifo"
    
    #endif
    

    2. Server Process (server.c)

    // server.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For read, write, close
    #include <string.h>
    #include <ctype.h>
    #include "common.h"
    
    #define BUFFER_SIZE 256
    
    // Function to evaluate simple expressions like "5 + 3"
    int evaluate_expression(const char* expression, char* result, size_t result_size) {
        int operand1, operand2;
        char operator;
    
        // Parse the expression
        if (sscanf(expression, "%d %c %d", &operand1, &operator, &operand2) != 3) {
            snprintf(result, result_size, "Error: Invalid expression format.\n");
            return -1;
        }
    
        int eval_result;
        switch (operator) {
            case '+':
                eval_result = operand1 + operand2;
                break;
            case '-':
                eval_result = operand1 - operand2;
                break;
            case '*':
                eval_result = operand1 * operand2;
                break;
            case '/':
                if (operand2 == 0) {
                    snprintf(result, result_size, "Error: Division by zero.\n");
                    return -1;
                }
                eval_result = operand1 / operand2;
                break;
            default:
                snprintf(result, result_size, "Error: Unsupported operator '%c'.\n", operator);
                return -1;
        }
    
        snprintf(result, result_size, "Result: %d\n", eval_result);
        return 0;
    }
    
    int main() {
        // Create FIFOs if they do not exist
        if (mkfifo(REQUEST_FIFO, 0666) == -1) {
            perror("mkfifo REQUEST_FIFO");
            // It's okay if the FIFO already exists
        }
    
        if (mkfifo(RESPONSE_FIFO, 0666) == -1) {
            perror("mkfifo RESPONSE_FIFO");
            // It's okay if the FIFO already exists
        }
    
        // Open FIFOs
        int request_fd = open(REQUEST_FIFO, O_RDONLY);
        if (request_fd == -1) {
            perror("open REQUEST_FIFO");
            exit(EXIT_FAILURE);
        }
    
        // Open the response FIFO for writing in non-blocking mode
        int response_fd = open(RESPONSE_FIFO, O_WRONLY);
        if (response_fd == -1) {
            perror("open RESPONSE_FIFO");
            close(request_fd);
            exit(EXIT_FAILURE);
        }
    
        char buffer[BUFFER_SIZE];
        printf("Server: Listening for expressions...\n");
    
        while (1) {
            // Read expression from request FIFO
            ssize_t bytesRead = read(request_fd, buffer, BUFFER_SIZE);
            if (bytesRead > 0) {
                buffer[bytesRead] = '\0'; // Null-terminate the string
                printf("Server: Received expression: %s", buffer);
    
                // Evaluate the expression
                char eval_result[BUFFER_SIZE];
                if (evaluate_expression(buffer, eval_result, BUFFER_SIZE) == -1) {
                    // Error in evaluation
                    // eval_result already contains the error message
                }
    
                // Send the result back via response FIFO
                if (write(response_fd, eval_result, strlen(eval_result) + 1) == -1) {
                    perror("write to RESPONSE_FIFO");
                } else {
                    printf("Server: Sent result: %s", eval_result);
                }
            } else if (bytesRead == 0) {
                // End of file (client has closed the FIFO)
                printf("Server: Client closed the FIFO. Exiting.\n");
                break;
            } else {
                perror("read from REQUEST_FIFO");
                break;
            }
        }
    
        // Close FIFOs
        close(request_fd);
        close(response_fd);
    
        // Unlink FIFOs
        unlink(REQUEST_FIFO);
        unlink(RESPONSE_FIFO);
    
        return 0;
    }
    

    3. Client Process (client.c)

    // client.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For read, write, close
    #include <string.h>
    #include "common.h"
    
    #define BUFFER_SIZE 256
    
    int main() {
        // Create FIFOs if they do not exist
        if (mkfifo(REQUEST_FIFO, 0666) == -1) {
            perror("mkfifo REQUEST_FIFO");
            // It's okay if the FIFO already exists
        }
    
        if (mkfifo(RESPONSE_FIFO, 0666) == -1) {
            perror("mkfifo RESPONSE_FIFO");
            // It's okay if the FIFO already exists
        }
    
        // Open FIFOs
        int request_fd = open(REQUEST_FIFO, O_WRONLY);
        if (request_fd == -1) {
            perror("open REQUEST_FIFO");
            exit(EXIT_FAILURE);
        }
    
        // Open the response FIFO for reading
        int response_fd = open(RESPONSE_FIFO, O_RDONLY);
        if (response_fd == -1) {
            perror("open RESPONSE_FIFO");
            close(request_fd);
            exit(EXIT_FAILURE);
        }
    
        char expression[BUFFER_SIZE];
        char result[BUFFER_SIZE];
    
        printf("Client: Enter mathematical expressions (e.g., 5 + 3). Type 'exit' to quit.\n");
    
        while (1) {
            // Get user input
            printf("Expression: ");
            if (fgets(expression, BUFFER_SIZE, stdin) == NULL) {
                perror("fgets");
                break;
            }
    
            // Remove newline character
            expression[strcspn(expression, "\n")] = '\0';
    
            // Check for exit condition
            if (strcmp(expression, "exit") == 0) {
                break;
            }
    
            // Send the expression to the server via request FIFO
            if (write(request_fd, expression, strlen(expression) + 1) == -1) {
                perror("write to REQUEST_FIFO");
                break;
            }
    
            // Read the result from the response FIFO
            ssize_t bytesRead = read(response_fd, result, BUFFER_SIZE);
            if (bytesRead > 0) {
                result[bytesRead] = '\0'; // Null-terminate
                printf("%s", result);
            } else if (bytesRead == 0) {
                printf("Client: Server closed the FIFO. Exiting.\n");
                break;
            } else {
                perror("read from RESPONSE_FIFO");
                break;
            }
        }
    
        // Close FIFOs
        close(request_fd);
        close(response_fd);
    
        // Unlink FIFOs
        unlink(REQUEST_FIFO);
        unlink(RESPONSE_FIFO);
    
        return 0;
    }
    

    4. Compilation Instructions

    Use gcc to compile both programs.

    gcc -o server server.c
    gcc -o client client.c
    

    5. Running the Programs

    1. Start the Server: Open a terminal and run the server program first.

      ./server
      

      Output:

      Server: Listening for expressions...
      
    2. Start the Client: Open another terminal and run the client program.

      ./client
      

      Output:

      Client: Enter mathematical expressions (e.g., 5 + 3). Type 'exit' to quit.
      Expression:
      
    3. Send Expressions and Receive Results

      Example:

      • Client Terminal:

        Expression: 10 + 5
        Result: 15
        
        Expression: 20 - 8
        Result: 12
        
        Expression: 7 * 6
        Result: 42
        
        Expression: 40 / 5
        Result: 8
        
        Expression: exit
        
      • Server Terminal:

        Server: Listening for expressions...
        Server: Received expression: 10 + 5
        Server: Sent result: Result: 15
        Server: Received expression: 20 - 8
        Server: Sent result: Result: 12
        Server: Received expression: 7 * 6
        Server: Sent result: Result: 42
        Server: Received expression: 40 / 5
        Server: Sent result: Result: 8
        Server: Received expression: exit
        Server: Client closed the FIFO. Exiting.
        
    4. Termination: The client can type exit to terminate. Both processes will unlink (remove) the FIFOs upon exiting.

    Notes on Handling Multiple Requests

    • Sequential Handling: The server handles one request at a time in the order they are received. For a simple system, this is sufficient.
    • Blocking Behavior: The client waits for the server's response after sending an expression, ensuring synchronization between requests and responses.
    • Error Handling: The server returns error messages for invalid expressions, which the client displays.

    Potential Improvements

    • Concurrency: For handling multiple clients simultaneously, the server can be enhanced to fork a new process/thread for each client connection.
    • Robust Parsing and Evaluation: Implement a more robust expression parser to handle complex expressions and ensure security.
    • Timeouts: Implement timeouts in the client to handle cases where the server does not respond.

    Task 4: Temperature Monitoring System with Multiple Sensors

    Scenario Recap

    • Sensor Processes (sensor1.c, sensor2.c, sensor3.c): Each simulates reading a temperature value (random between 20°C and 30°C) every 3 seconds and writes it to its own FIFO pipe.
    • Central Monitor Process: Reads temperatures from all three FIFOs and displays them in real-time.
    • Concurrency Handling: Ensure the monitor can handle incoming data simultaneously from all sensors.

    Solution Overview

    1. Create Three Named Pipes (FIFOs): One for each sensor.
      • sensor1_fifo
      • sensor2_fifo
      • sensor3_fifo
    2. Sensor Processes (sensor1.c, etc.):
      • Each opens its own FIFO for writing.
      • Every 3 seconds, generates a random temperature and writes it to the FIFO.
    3. Central Monitor Process (monitor.c):
      • Opens all three FIFOs for reading.
      • Uses select() or poll() to monitor multiple FIFOs simultaneously.
      • Reads incoming data and displays temperatures with sensor identification.
    4. Concurrency: Use non-blocking I/O or multiplexing (select()) to handle multiple FIFOs without blocking.
    5. Clean Up: Remove FIFOs upon termination.

    Implementation

    1. Defining FIFO Paths

    We'll define separate FIFO paths for each sensor in a common header.

    // common.h
    #ifndef COMMON_H
    #define COMMON_H
    
    #define SENSOR1_FIFO "sensor1_fifo"
    #define SENSOR2_FIFO "sensor2_fifo"
    #define SENSOR3_FIFO "sensor3_fifo"
    
    #endif
    

    2. Sensor Processes (sensor1.c, sensor2.c, sensor3.c)

    Since all sensor programs are similar except for their FIFO names, we can parameterize them or write separate code for each.

    For simplicity, I'll provide a generic sensor code that takes the FIFO path as a command-line argument. You can compile it into three separate executables or create three separate source files.

    Option 1: Generic Sensor (sensor.c)

    // sensor.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For write, close, sleep
    #include <time.h>
    #include <string.h>
    #include "common.h"
    
    #define BUFFER_SIZE 256
    
    int main(int argc, char* argv[]) {
        if (argc != 2) {
            fprintf(stderr, "Usage: %s <sensor_fifo>\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    
        const char* fifo_path = argv[1];
    
        // Seed random number generator
        srand(time(NULL) ^ getpid());
    
        // Create the FIFO if it does not exist
        if (mkfifo(fifo_path, 0666) == -1) {
            perror("mkfifo");
            // It's okay if the FIFO already exists
        }
    
        // Open the FIFO for writing
        int fd = open(fifo_path, O_WRONLY);
        if (fd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
    
        while (1) {
            // Generate a random temperature between 20 and 30
            int temperature = (rand() % 11) + 20; // 20 to 30 inclusive
    
            // Get current time
            time_t now = time(NULL);
            struct tm* tm_info = localtime(&now);
            char time_str[26];
            strftime(time_str, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    
            // Prepare the temperature reading
            char temp_reading[BUFFER_SIZE];
            snprintf(temp_reading, BUFFER_SIZE, "[%s] Temperature: %d°C\n", time_str, temperature);
    
            // Write the temperature to FIFO
            if (write(fd, temp_reading, strlen(temp_reading) + 1) == -1) {
                perror("write");
                break;
            }
    
            printf("Sensor (%s): Sent temperature: %d°C\n", fifo_path, temperature);
    
            // Sleep for 3 seconds
            sleep(3);
        }
    
        // Close the FIFO
        close(fd);
    
        // Unlink the FIFO
        unlink(fifo_path);
    
        return 0;
    }
    

    Compilation and Creation of Sensor Executables

    Compile once and run with different FIFO paths.

    gcc -o sensor sensor.c
    

    Running Sensors

    Run three instances of the sensor program with different FIFO paths.

    ./sensor sensor1_fifo
    ./sensor sensor2_fifo
    ./sensor sensor3_fifo
    

    Alternatively, create separate source files sensor1.c, sensor2.c, sensor3.c each hardcoding their FIFO paths:

    // sensor1.c
    #include "sensor.c" // Or duplicate the code with SENSOR1_FIFO
    
    // Similarly for sensor2.c and sensor3.c
    

    But the generic approach is more maintainable.

    3. Central Monitor Process (monitor.c)

    // monitor.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>      // For open
    #include <sys/stat.h>   // For mkfifo
    #include <unistd.h>     // For read, close, unlink
    #include <string.h>
    #include <sys/select.h>
    #include "common.h"
    
    #define BUFFER_SIZE 256
    
    int main() {
        // Create FIFOs if they do not exist
        if (mkfifo(SENSOR1_FIFO, 0666) == -1) {
            perror("mkfifo SENSOR1_FIFO");
            // It's okay if FIFO exists
        }
        if (mkfifo(SENSOR2_FIFO, 0666) == -1) {
            perror("mkfifo SENSOR2_FIFO");
        }
        if (mkfifo(SENSOR3_FIFO, 0666) == -1) {
            perror("mkfifo SENSOR3_FIFO");
        }
    
        // Open all three FIFOs for reading
        int fd1 = open(SENSOR1_FIFO, O_RDONLY | O_NONBLOCK);
        if (fd1 == -1) {
            perror("open SENSOR1_FIFO");
            exit(EXIT_FAILURE);
        }
    
        int fd2 = open(SENSOR2_FIFO, O_RDONLY | O_NONBLOCK);
        if (fd2 == -1) {
            perror("open SENSOR2_FIFO");
            close(fd1);
            exit(EXIT_FAILURE);
        }
    
        int fd3 = open(SENSOR3_FIFO, O_RDONLY | O_NONBLOCK);
        if (fd3 == -1) {
            perror("open SENSOR3_FIFO");
            close(fd1);
            close(fd2);
            exit(EXIT_FAILURE);
        }
    
        printf("Monitor: Listening to all sensors...\n");
    
        fd_set read_fds;
        int max_fd = fd1;
        if (fd2 > max_fd) max_fd = fd2;
        if (fd3 > max_fd) max_fd = fd3;
    
        char buffer[BUFFER_SIZE];
        while (1) {
            FD_ZERO(&read_fds);
            FD_SET(fd1, &read_fds);
            FD_SET(fd2, &read_fds);
            FD_SET(fd3, &read_fds);
    
            // Wait indefinitely for any of the FIFOs to have data
            int ret = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
            if (ret == -1) {
                perror("select");
                break;
            }
    
            // Check each FIFO
            if (FD_ISSET(fd1, &read_fds)) {
                ssize_t bytesRead = read(fd1, buffer, BUFFER_SIZE);
                if (bytesRead > 0) {
                    buffer[bytesRead] = '\0';
                    printf("Monitor: [Sensor1] %s", buffer);
                }
            }
    
            if (FD_ISSET(fd2, &read_fds)) {
                ssize_t bytesRead = read(fd2, buffer, BUFFER_SIZE);
                if (bytesRead > 0) {
                    buffer[bytesRead] = '\0';
                    printf("Monitor: [Sensor2] %s", buffer);
                }
            }
    
            if (FD_ISSET(fd3, &read_fds)) {
                ssize_t bytesRead = read(fd3, buffer, BUFFER_SIZE);
                if (bytesRead > 0) {
                    buffer[bytesRead] = '\0';
                    printf("Monitor: [Sensor3] %s", buffer);
                }
            }
        }
    
        // Close FIFOs
        close(fd1);
        close(fd2);
        close(fd3);
    
        // Unlink FIFOs
        unlink(SENSOR1_FIFO);
        unlink(SENSOR2_FIFO);
        unlink(SENSOR3_FIFO);
    
        return 0;
    }
    

    4. Compilation Instructions

    gcc -o sensor sensor.c
    gcc -o monitor monitor.c
    

    5. Running the Programs

    1. Start the Central Monitor: Open a terminal and run the monitor program first.

      ./monitor
      

      Output:

      Monitor: Listening to all sensors...
      
    2. Start the Sensors: Open three separate terminals (or use background processes) and run each sensor.

      ./sensor sensor1_fifo
      ./sensor sensor2_fifo
      ./sensor sensor3_fifo
      

      Example Sensor Output (sensor1_fifo):

      Sensor (sensor1_fifo): Sent temperature: 25°C
      Sensor (sensor1_fifo): Sent temperature: 22°C
      ...
      
    3. Monitor Output: The monitor terminal will display incoming temperature readings from all sensors in real-time.

      Monitor: [Sensor1] [2023-10-10 12:05:01] Temperature: 25°C
      Monitor: [Sensor2] [2023-10-10 12:05:01] Temperature: 27°C
      Monitor: [Sensor3] [2023-10-10 12:05:01] Temperature: 23°C
      Monitor: [Sensor1] [2023-10-10 12:05:04] Temperature: 22°C
      Monitor: [Sensor2] [2023-10-10 12:05:04] Temperature: 24°C
      Monitor: [Sensor3] [2023-10-10 12:05:04] Temperature: 26°C
      ...
      
    4. Termination: To terminate, you can use Ctrl+C in the monitor terminal and each sensor terminal. Ensure all processes terminate to clean up FIFOs properly.

    Notes on Concurrency Handling

    • Using select(): The monitor uses select() to monitor multiple FIFOs simultaneously. This allows it to respond to incoming data from any sensor without blocking.
    • Non-Blocking Mode: The FIFOs are opened in non-blocking mode (O_NONBLOCK) to prevent the monitor from blocking if no data is available on a FIFO.
    • Real-Time Display: As each sensor writes data, the monitor immediately reads and displays it, ensuring real-time monitoring.
    • Handling FIFO Closure: If a sensor terminates, the corresponding read end in the monitor may receive EOF. Proper handling can be added to manage sensor restarts.
    • Scalability: While this example uses three sensors, the monitor can be extended to handle more sensors by adding more FIFO descriptors and updating the select() logic.

    General Notes for All Tasks

    1. FIFO Creation: Ensure that FIFOs are created before the processes that use them start. Typically, this means starting the receiver or server processes first.

    2. Permissions: The mkfifo() function sets permissions for the FIFO. The mode 0666 allows read and write for all users. Adjust permissions as needed for your use case.

    3. Avoiding Deadlocks: Ensure that both ends of the FIFO are opened appropriately. For example, opening a FIFO for reading will block until another process opens it for writing, and vice versa.

    4. Error Handling: Always check the return values of system calls (mkfifo(), open(), read(), write(), etc.) and handle errors gracefully to prevent crashes or resource leaks.

    5. Resource Cleanup: Always close file descriptors after use and unlink FIFOs when they are no longer needed to prevent resource leaks.

    6. Concurrency: When dealing with multiple readers or writers, ensure that the communication protocol between processes is well-defined to prevent race conditions or data corruption.

    7. Security: When accepting input from users (as in the client-server system), validate and sanitize inputs to prevent security vulnerabilities.

    8. Scalability and Performance: For high-throughput or high-concurrency systems, consider more efficient IPC mechanisms or enhancements to the FIFO-based approach.

    By following these implementations and best practices, you can effectively build robust inter-process communication systems using FIFO pipes in C.