I want to capture the Ctrl+D signal in my program and write a signal handler for it. How can I do that? I am working on C and using a Linux system.
I want to capture the Ctrl+D signal in my program and write a signal handler for it. How can I do that? I am working on C and using a Linux system.
Ctrl + D value in ascci table is 4 and is a non printable characters.
So your can capture it in a terminal with the following code.
When getline function get Ctrl + D an error occur and return value is -1.
Your can make a condition on the return value.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buf = malloc(sizeof(char) * 500);
size_t size = 500;
int nb = getline(&buf, &size, stdin);
if (nb == -1)
printf("CTRL + D captured\n");
free(buf);
return (0);
}
You can check if stdin is not of with the feof method like so:
if (feof(stdin))
{
// some code
exit(0);
}
See this for more details/