The problem: I need to print the kill signal received by a process,
For example:
If I send a *kill -15 1245*
where 1245 is the pid of my process, my program should print something like "Process killed by signal 15"
, but even If I send a *kill -15*
to a process, the WIFSIGNALED macro returns false and obviously WTERMSIG returns 0.
The system: I'm on Linux Mint 18.3, an Ubuntu based distro, and I tested my program in other Ubuntu distros and still does not working, BUT in Fedora and OpenSUSE it works well. Any idea?
The code:
//Libraries
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
//Macros
#define MAX_LIMIT 50
//Function where i create a child process and execute a shell over it.
void run(char comando[])
{
int status;
pid_t pid;
if((pid = fork()) == 0)
execlp("sh", "sh", "-c", comando, NULL);
pid = waitpid(pid, &status, 0);
//The problem begins here, the WIFEXITED returns *true* even is the process was killed by a signal.
if(WIFEXITED(status))
printf("Process ended with status %d\n",
WEXITSTATUS(status));
//Is here when i need to print the signal, but WIFSIGNALED returns *false* even if a signal was sended by the *kill* command.
else if(WIFSIGNALED(status))
printf("Process killed by signal %d\n",
WTERMSIG(status));
else if(WIFSTOPPED(status))
printf("Process stopped by signal %d\n",
WSTOPSIG(status));
else if(WIFCONTINUED(status))
printf("Process continued...\n");
}
//Function that simulates a shell by repeating prompt.
void shell()
{
run("clear");
printf("\t\t\t\t\tMINI_SHELL\n");
char comando[MAX_LIMIT];
do
{
printf("$> ");
fgets(comando, MAX_LIMIT, stdin);
char *cp = strchr(comando,'\n'); if (cp != NULL) *cp = 0;
if(strcmp(comando, "ext") != 0)
run(comando);
} while(strcmp(comando, "ext") != 0);
}
int main(int argc, char *argv[])
{
shell();
return 0;
}