Signal Handling in Three Languages
December 21, 2024
note-to-self
Signal processing in three scripting languages:
PHP
<?php
function handleSignal($signal) {
echo "Received {$signal}..." . PHP_EOL;
switch ($signal) {
case SIGTERM:
// maybe close stuff, etc
exit 0;
case SIGINT:
// maybe close stuff, etc
exit 0;
}
}
pcntl_signal(SIGTERM, "handleSignal");
pcntl_signal(SIGINT, "handleSignal");
while (true) {
pcntl_signal_dispatch();
echo "Running..." . PHP_EOL;
sleep(10);
}
Run:
> php signal.php
# in another terminal window
> kill -TERM $(ps ax|grep "php signal.php"|grep -v "php"|awk '{print $1}')
Javascript
console.log(' Request started: ' + (new Date));
handleSignal = signal => {
let dt = (new Date)
console.log(` Received ${signal} at ${dt}, shutting down gracefully...`);
}
process.on('SIGTERM', signal => {
handleSignal(signal)
});
process.on('SIGQUIT', signal => {
handleSignal(signal)
});
process.on('SIGINT', signal => {
handleSignal(signal)
});
console.log(' Request started: ' + (new Date));
console.log(' firing off req 1')
fetch('https://<website>/sleep.php?t=10')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(' Data fetched successfully:', data);
console.log(' At: ' + (new Date));
})
.catch(error => {
console.error(' Error fetching data:', error);
console.log(' At: ' + (new Date));
});
Run:
> node signal.js
# in another terminal window
> kill -TERM $(ps ax|grep "node signal.js"|grep -v "node"|awk '{print $1}')
Bash
#!/bin/bash
handleSignal() {
echo "Received signal."
exit 0
}
trap handleSignal SIGTERM
trap handleSignal SIGINT
while true; do
echo "Running..."
sleep 10
done
Run:
> bash signal.sh
# in another terminal window
> kill -TERM $(ps ax|grep "bash signal.sh"|grep -v "bash"|awk '{print $1}')