Run multiple copies of the signals.c code from different terminals. This will gi
ID: 3717897 • Letter: R
Question
Run multiple copies of the signals.c code from different terminals. This will give you a list of process IDs related to this code. Change your shell script to catch all the Process IDs associated with the signals.c code and first send a SIGINT and then a SIGKILL to each. You will find the following command useful:
for pid in `ps -ef | grep your_search_term | awk '{print $2}'` ; do kill $pid ; done
Shellscript file:
#!/bin/bash
echo pid
read pid
#pid=185817
echo "Killing process $pid..."
kill -SIGINT $pid
waitAttempts=30
for i in $(seq 1 $waitAttempts)
do
echo "Checking if process is alive (attempt #$i / $waitAttempts)..."
sleep 1
if ps -p $pid > /dev/null
then
echo "Process $pid is still running"
else
echo "Process $pid has shut down successfully"
break
fi
done
if ps -p $pid > /dev/null
then
echo "Could not shut down process $pid gracefully - killing it forcibly..."
kill -SIGKILL $pid
fi
Signals.c:
#include<stdio.h>
#include<signal.h>
void signal_handler( int no ) {
printf("Signals received : %d ", no );
if ( no == SIGHUP ) {
printf( "Signal handler got a SIGHUP! " );
}
else if ( no == SIGINT ) {
printf( "Signal handler got a SIGNINT! " );
}
return;
}
void cleanup_handler( int no ) {
return; // Cleanup here
}
int main( void ) {
struct sigaction new_action, old_action; // Setup the signal actions
new_action.sa_handler = signal_handler;
new_action.sa_flags = SA_NODEFER | SA_ONSTACK;
sigaction( SIGINT, &new_action, &old_action );
signal( SIGHUP, signal_handler ); // Setup the signal handlers
signal( SIGTERM, cleanup_handler );
while (1) {
printf( "Sleeping ...zzzzz .... " );
select( 0, NULL, NULL, NULL, NULL );
printf( "Woken up!! " );
}
// Return successfully
return( 0 );
}
Explanation / Answer
kill.sh
*******
#!/bin/bash
echo pid
read pid
#pid=185817
echo "Killing process $pid..."
kill -SIGINT $pid
waitAttempts=5
for i in $(seq 1 $waitAttempts)
do
echo "Checking if process is alive (attempt #$i / $waitAttempts)..."
sleep 1
if ps -p $pid > /dev/null
then
echo "Process $pid is still running"
else
echo "Process $pid has shut down successfully"
break
fi
done
PID=`ps -eaf | grep a.out | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi
in above code of your signal.c i create a.out executable file and then reference it over here in my shell script in below line
PID=`ps -eaf | grep a.out | grep -v grep | awk '{print $2}'`
Thanks lf you need more help let me know but dont thumb down , rate me thumbs up for me
Regards
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.