I am trying to implement a script in which a pipe is getting created and the default value 0 is stored in the pipe. Simultaneously, a c code file is getting executed which based on a condition updates the value in pipe to 1.
In the script, the pipe value is being read continuously, based on which if the pipe value is updated then another variable’s flag value will be changed to 1 and the loop will end. But the problem is that read takes a lot time to read due to which the script is getting stuck inspite of using the timeout feature.
#!/bin/bash
pipe_name="/tmp/my_pipe"
initial_value="0"
# Create the named pipe if it does not exist
if [ ! -p "$pipe_name" ]; then
mkfifo "$pipe_name"
fi
# Function to initialize the pipe with the initial value
initialize_pipe() {
echo "$initial_value" > "$pipe_name" &
}
# Initialize the pipe
initialize_pipe
STOP_FH_LOGS="$initial_value"
while true; do
# Using read with a timeout to avoid blocking indefinitely
if read -t 1 new_value < "$pipe_name"; then
STOP_FH_LOGS=$new_value
# Check the read value and write it back to the pipe
if [ "$STOP_FH_LOGS" = "0" ]; then
echo "$STOP_FH_LOGS" > "$pipe_name" &
echo "Condition still 0"
elif [ "$STOP_FH_LOGS" = "1" ]; then
echo "Value changed to 1"
break
else
echo "New STOP_FH_LOGS error value: $STOP_FH_LOGS"
# Optionally, write back the new value if needed
echo "$STOP_FH_LOGS" > "$pipe_name" &
fi
else
# Handle timeout or no data read scenario
echo "Timeout or no data read"
# Ensure the pipe is not empty
if [ ! -p "$pipe_name" ]; then
initialize_pipe
fi
fi
done
A sample c code trying to change the code in the pipe is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define PIPE_NAME "/tmp/my_pipe"
#define INITIAL_VALUE "0"
#define NEW_VALUE "1"
void write_to_pipe(const char *value) {
int pipe_fd = open(PIPE_NAME, O_WRONLY);
if (pipe_fd == -1) {
perror("Failed to open pipe for writing");
exit(EXIT_FAILURE);
}
if (write(pipe_fd, value, strlen(value)) == -1) {
perror("Failed to write to pipe");
close(pipe_fd);
exit(EXIT_FAILURE);
}
close(pipe_fd);
}
int main() {
char buffer[2];
int pipe_fd;
while (1) {
pipe_fd = open(PIPE_NAME, O_RDONLY);
if (pipe_fd == -1) {
perror("Failed to open pipe for reading");
exit(EXIT_FAILURE);
}
ssize_t num_read = read(pipe_fd, buffer, 1);
if (num_read == -1) {
perror("Pipe read error");
close(pipe_fd);
exit(EXIT_FAILURE);
}
buffer[num_read] = '';
close(pipe_fd);
// Check if the current value is "0"
if (strcmp(buffer, "0") == 0) {
write_to_pipe(NEW_VALUE);
break;
}
sleep(1); // Sleep to avoid busy-waiting
}
return 0;
}
Tried the timeout condition but it is still getting stuck, so need suggestions as to what can be done
Abhir Raj Shrivastava is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.