185k views
1 vote
Write a script that counts how many times a user tries to quit the program with an interrupt (typically Control-C), showing the count and finally letting them quit on the fifth attempt. Tip: You'll need to use trap for this, and the interrupt signal is SIGINT.

1 Answer

2 votes

Final answer:

The question is about writing a bash script to count the number of times a user attempts to quit using Control-C. A trap command is used to handle the SIGINT signal and a counter increases each time the signal is received. On the fifth attempt, the script exits.

Step-by-step explanation:

The question involves writing a script that uses a trap command to count how many times the user has tried to exit the program using an interrupt signal, typically Control-C, which corresponds to SIGINT. On the fifth attempt, the program should allow the user to quit. This script can be written in bash, which is often used for such tasks on Unix-like operating systems.

Here is an example of how the script might look:

#!/bin/bash

# Initialize a counter for the interrupt signals
count=0

# Define a function to handle the SIGINT signal
handle_sigint() {
let "count+=1"
echo "Interrupt signal received $count times"
if [ $count -eq 5 ]; then
echo "Exiting program..."
exit
fi
}

# Trap the SIGINT signal and attach it to the handle_sigint function
trap 'handle_sigint' SIGINT

# An infinite loop to keep the script running
while true; do
:
done

In this script, we're using the trap command to capture the SIGINT signal and link it to a function called handle_sigint that increments a counter, prints the current count, and exits if the count is equal to five. The script stays running due to an infinite loop that does nothing (represented by the colon).

User ZeppRock
by
7.9k points