The code I have right now sends a prompt out to stdout, then reads a line from stdin. Receiving SIGINT at any point interrupts execution and exits the program. I am unsure where I should trap SIGINT, and I know that I cannot start a new prompt when the signal is received with my current code. Is there a proper way to accomplish that (ultimate goal would be for it to act like most shells (SIGINT cancels the current prompt and starts a new one))?
This code will run on Linux, but the less platform independent, the better.
get_line reads a line from stdin into a buffer and generates a char[], which is assigned to line.
split_args takes a line and transforms it into an array of char[], splitting on whitespace.
is_command_valid determines if the user typed a known internal command. External programs cannot be executed.
static int run_interactive(char *user)
{
int done = 0;
do
{
char *line, **args;
int (*fn)(char *, char **);
fprintf(stderr, "gitorium (%s)> ", user);
get_line(&line);
if (line[0] == '\0')
{
free(line);
break;
}
split_args(&args, line);
if (!strcmp(args[0], "quit") || !strcmp(args[0], "exit") ||
!strcmp(args[0], "logout") || !strcmp(args[0], "bye"))
done = 1;
else if (NULL == args[0] ||
(!strcmp("help", args[0]) && NULL == args[1]))
interactive_help();
else if ((fn = is_command_valid(args)) != NULL)
(*fn)(user, args);
else
error("The command does not exist.");
free(line);
free(args);
}
while (!done);
return 0;
}
Here are the two most important helper functions
static int split_args(char ***args, char *str)
{
char **res = NULL, *p = strtok(str, " ");
int n_spaces = 0, i = 0;
while (p)
{
res = realloc(res, sizeof (char*) * ++n_spaces);
if (res == NULL)
return GITORIUM_MEM_ALLOC;
res[n_spaces-1] = p;
i++;
p = strtok(NULL, " ");
}
res = realloc(res, sizeof(char*) * (n_spaces+1));
if (res == NULL)
return GITORIUM_MEM_ALLOC;
res[n_spaces] = 0;
*args = res;
return i;
}
static int get_line(char **linep)
{
char *line = malloc(LINE_BUFFER_SIZE);
int len = LINE_BUFFER_SIZE, c;
*linep = line;
if(line == NULL)
return GITORIUM_MEM_ALLOC;
for(;;)
{
c = fgetc(stdin);
if(c == EOF || c == '\n')
break;
if(--len == 0)
{
char *linen = realloc(*linep, sizeof *linep + LINE_BUFFER_SIZE);
if(linen == NULL)
return GITORIUM_MEM_ALLOC;
len = LINE_BUFFER_SIZE;
line = linen + (line - *linep);
*linep = linen;
}
*line++ = c;
}
*line = 0;
return 0;
}
If I understand you correctly, you want to know how to handle the signal as well as what to do once you get it.
The way you establish a signal handler is with sigaction(). You didn't state the platform you're on so I'm assuming Linux, although sigaction() is defined by the POSIX standards and should be available on most other platforms.
There are various ways you can do this. One way is to establish a signal handler which simply sets a global variable to 1, denoting that the signal was caught. Then in your getline() function you establish a check to see if SIGINT was caught and if it was then return NULL and allow run_interactive() to run again.
Here's how you would catch the signal:
#include <signal.h>
static int sigint_caught = 0;
static void sigint_handler(int sig) {
sigint_caught = 1;
}
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0; // or SA_RESTART if you want to automatically restart system calls interrupted by the signal
sa.sa_handler = sigint_handler;
if (sigaction(SIGINT, &sa, NULL) == -1) {
printf("could not establish handler\n");
exit(-1); // or something
}
And then perhaps in getline(), in the infinite loop, you would establish the check to see if SIGINT has been caught:
for (;;) {
if (sigint_caught) {
return NULL;
}
// ...
And then in your run_interactive() call you can check the return value with the check to see if SIGINT was caught:
// ...
get_line(&line);
if (line == NULL && sigint_caught) {
sigint_caught = 0; // allow it to be caught again
free(line);
continue; // or something; basically go to the next iteration of this loop
} else if (line[0] == '\0') {
free(line);
break;
} else {
// rest of code
Didn't test it so I can't guarantee it'll work, since your question is pretty broad (having to look through more of your code etc.), but hopefully it gives you enough of an idea as to what you can do you in your situation. This is perhaps a pretty naive solution but it might meet your needs. For something more robust perhaps look into the source code for popular shells like bash or zsh.
For example, one thing that can happen is that fgetc() might block since there is no new data in stdin, and that might be when the signal is sent. fgetc() would be interrupted and errno would be EINTR, so you could add a check for this in getline():
c = fgetc(stdin);
// make sure to #include <errno.h>
if (errno == EINTR && sigint_caught)
return NULL;
This would only happen if you don't set sa_flags to SA_RESTART. If you do, then fgetc should automatically restart and continue blocking until new input is received, which may or may not be what you want.
Related
I have this child process in infinite loop and i want it to stop the loop when recive SIGUSR1 from parent pid.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
int GameOver = 0;
jmp_buf here; // <------- After Joshua's Answer
void trataSIGUSR1(int sig, siginfo_t *info, void *extra);
int main(int argc, char** argv){
int someNumber = 0, score = 0;
char word[15],c;
struct sigaction new_action;
// new_action.sa_flags = SA_SIGINFO; // <------- Before Joshua's Answer
new_action.sa_flags = SA_SIGINFO | SA_RESTART; // <------- After Joshua's Answer
new_action.sa_sigaction = &trataSIGUSR1;
sigfillset(&new_action.sa_mask);
if (sigaction(SIGUSR1, &new_action, NULL) == -1){
perror("Error: cannot handle SIGUSR1"); // não deve acontecer
return EXIT_FAILURE;
}
FILE *f;
f = fopen("randomfile.txt", "r");
if (f == NULL){
printf("Errr Opening File!\n");
return EXIT_FAILURE;
}
// setjmp(here); // <------- After Joshua's Answer
sigsetjmp(here,1); // <-- After wildplasser's Answer
while (!GameOver){
fscanf(f, "%s", word);
printf("\nWord -> %s\n", word);
if(!scanf("%d", &someNumber)){
puts("Invalid Value!");
while ((c = getchar()) != '\n' && c != EOF);
continue;
}
if(someNumber == strlen(word) && !GameOver)
score ++;
if(feof(f)){
printf("\nEnd of file.\n");
break;
}
}
if( GameOver )
puts("\nAcabou o tempo!"); // <-- After wildplasser's Answer
fclose(f);
return score;
}
void trataSIGUSR1(int sig, siginfo_t *info, void *extra){
if (info->si_pid == getppid()){ // only end when parent send SIGUSR1
// puts("\nAcabou o tempo!"); // <-- Before wildplasser's Answer
GameOver = 1;
// longjmp(here,1); // <------- After Joshua's Answer
siglongjmp(here,1); // <---- After wildplasser's Answer
}
}
It works fine but if i send SIGUSR1 to child pid from another process scanf get interupted... I want to interupt the scanf and automaticly stop the loop only when signal come from parent, in other case just ignore. Is there any way to change the flag to new_action.sa_flags = SA_RESTART; when signal comes from other process?!
There are several possibilities, ranging from a huge hack, to proper (but complicated).
The simplest thing is to have the SIGUSR1 from parent reopen standard input to /dev/null. Then, when scanf() fails, instead of complaining and retrying, you can break out of the loop if feof(stdin) is true. Unfortunately, freopen() is not async-signal safe, so this is not a standards (POSIX, in this case) compliant way of doing things.
The standards-compliant way of doing things is to implement your own read input line into a dynamically allocated string -type of function, which detects when the signal handler sets the flag. The flag should also be of volatile sig_atomic_t type, not an int; the volatile in particular tells the compiler that the value may be changed unexpectedly (by the signal handler), so whenever referenced, the compiler must re-read the variable value, instead of remembering it from a previous access. The sig_atomic_t type is an atomic integer type: the process and the signal handler will only ever see either the new, or the old value, never a mix of the two, but might have as small valid range as 0 to 127, inclusive.
Signal delivery to an userspace handler (installed without SA_RESTART) does interrupt a blocking I/O operation (like read or write; in the thread used for signal delivery – you only have one, so that will always be used), but it might occur between the flag check and the scanf(), so in this case, it is not reliable.
The proper solution here is to not use stdin at all, and instead use the low-level <unistd.h> I/O for this. Note that it is imperative to not mix stdin/scanf() and low-level I/O for the same stream. You can safely use printf(), fprintf(stdout, ...), fprintf(stderr, ...), and so on. The reason is that the C library internal stdin stream structure will not be updated correctly by our low-level access, and will be out-of-sync with reality if we mix both (for the same stream).
Here is an example program showing one implementation (licensed under Creative Commons Zero v1.0 International – do as you wish with it, no guarantees though):
// SPDX-License-Identifier: CC0-1.0
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
/* Maximum poll() timeout, in milliseconds, so that done flag is checked often enough.
*/
#ifndef DONE_POLL_INTERVAL_MS
#define DONE_POLL_INTERVAL_MS 100
#endif
static volatile sig_atomic_t done = 0;
static void handle_done(int signum, siginfo_t *info, void *context)
{
/* This silences warnings about context not being used. It does nothing. */
(void)context;
if (signum == SIGUSR1 && info->si_pid == getppid()) {
/* SIGUSR1 is only accepted if it comes from the parent process */
done = 1;
} else {
/* All other signals are accepted from all processes (that have the necessary privileges) */
done = 1;
}
}
static int install_done(const int signum)
{
struct sigaction act;
memset(&act, 0, sizeof act);
sigemptyset(&(act.sa_mask));
act.sa_sigaction = handle_done;
act.sa_flags = SA_SIGINFO;
return sigaction(signum, &act, NULL);
}
/* Our own input stream structure type. */
struct input {
int descriptor;
char *data;
size_t size;
size_t head;
size_t tail;
};
/* Associating an input stream with a file descriptor.
Do not mix stdin use and input stream on descriptor STDIN_FILENO!
*/
static int input_use(struct input *const in, const int descriptor)
{
/* Check that the parameters are not obviously invalid. */
if (!in || descriptor == -1) {
errno = EINVAL;
return -1;
}
/* Set the descriptor nonblocking. */
{
int flags = fcntl(descriptor, F_GETFL);
if (flags == -1) {
/* errno set by fcntl(). */
return -1;
}
if (fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == -1) {
/* errno set by fcntl(). */
return -1;
}
}
/* Initialize the stream structure. */
in->descriptor = descriptor;
in->data = NULL;
in->size = 0;
in->head = 0;
in->tail = 0;
/* Success. */
return 0;
}
/* Read until delimiter from an input stream.
* If 'done' is set at any point, will return 0 with errno==EINTR.
* Returns 0 if an error occurs, with errno set.
* Returns 0 with errno==0 when end of input stream.
*/
static size_t input_getdelim(struct input *const in,
int const delim,
char **const dataptr,
size_t *const sizeptr,
const double timeout)
{
const clockid_t timeout_clk = CLOCK_BOOTTIME;
struct timespec then;
/* Verify none of the pointers are NULL. */
if (!in || !dataptr || !sizeptr) {
errno = EINVAL;
return 0;
}
/* Record current time for timeout measurement. */
clock_gettime(timeout_clk, &then);
char *line_data = *dataptr;
size_t line_size = *sizeptr;
/* If (*sizeptr) is zero, then we ignore dataptr value, like getline() does. */
if (!line_size)
line_data = NULL;
while (1) {
struct timespec now;
struct pollfd fds[1];
ssize_t n;
int ms = DONE_POLL_INTERVAL_MS;
/* Done flag set? */
if (done) {
errno = EINTR;
return 0;
}
/* Is there a complete line in the input buffer? */
if (in->tail > in->head) {
const char *ptr = memchr(in->data + in->head, delim, in->tail - in->head);
if (ptr) {
const size_t len = ptr - (in->data + in->head);
if (len + 2 > line_size) {
/* Since we do not have any meaningful data in line_data,
and it would be overwritten anyway if there was,
instead of reallocating it we just free an allocate it. */
free(line_data); /* Note: free(null) is safe. */
line_size = len + 2;
line_data = malloc(line_size);
if (!line_data) {
/* Oops, we lost the buffer. */
*dataptr = NULL;
*sizeptr = 0;
errno = ENOMEM;
return 0;
}
*dataptr = line_data;
*sizeptr = line_size;
}
/* Copy the line, including the separator, */
memcpy(line_data, in->data + in->head, len + 1);
/* add a terminating nul char, */
line_data[len + 1] = '\0';
/* and update stream buffer state. */
in->head += len + 1;
return len + 1;
}
/* No, we shall read more data. Prepare the buffer. */
if (in->head > 0) {
memmove(in->data, in->data + in->head, in->tail - in->head);
in->tail -= in->head;
in->head = 0;
}
} else {
/* Input buffer is empty. */
in->head = 0;
in->tail = 0;
}
/* Do we need to grow input stream buffer? */
if (in->head >= in->tail) {
/* TODO: Better buffer size growth policy! */
const size_t size = (in->tail + 65535) | 65537;
char *data;
data = realloc(in->data, size);
if (!data) {
errno = ENOMEM;
return 0;
}
in->data = data;
in->size = size;
}
/* Try to read additional data. It is imperative that the descriptor
has been marked nonblocking, as otherwise this will block. */
n = read(in->descriptor, in->data + in->tail, in->size - in->tail);
if (n > 0) {
/* We read more data without blocking. */
in->tail += n;
continue;
} else
if (n == 0) {
/* End of input mark (Ctrl+D at the beginning of line, if a terminal) */
const size_t len = in->tail - in->head;
if (len < 1) {
/* No data buffered, read end of input. */
if (line_size < 1) {
line_size = 1;
line_data = malloc(line_size);
if (!line_data) {
errno = ENOMEM;
return 0;
}
*dataptr = line_data;
*sizeptr = line_size;
}
line_data[0] = '\0';
errno = 0;
return 0;
}
if (len + 1 > line_size) {
/* Since we do not have any meaningful data in line_data,
and it would be overwritten anyway if there was,
instead of reallocating it we just free an allocate it. */
free(line_data); /* Note: free(null) is safe. */
line_size = len + 1;
line_data = malloc(line_size);
if (!line_data) {
/* Oops, we lost the buffer. */
*dataptr = NULL;
*sizeptr = 0;
errno = ENOMEM;
return 0;
}
*dataptr = line_data;
*sizeptr = line_size;
}
memmove(line_data, in->data, len);
line_data[len] = '\0';
in->head = 0;
in->tail = 0;
return 0;
} else
if (n != -1) {
/* This should never occur; it would be a C library bug. */
errno = EIO;
return 0;
} else {
const int err = errno;
if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR)
return 0;
/* EAGAIN, EWOULDBLOCK, and EINTR are not real errors. */
}
/* Nonblocking operation, with timeout == 0.0? */
if (timeout == 0.0) {
errno = ETIMEDOUT;
return 0;
} else
if (timeout > 0.0) {
/* Obtain current time. */
clock_gettime(timeout_clk, &now);
const double elapsed = (double)(now.tv_sec - then.tv_sec)
+ (double)(now.tv_nsec - then.tv_nsec) / 1000000000.0;
/* Timed out? */
if (elapsed >= (double)timeout / 1000.0) {
errno = ETIMEDOUT;
return 0;
}
if (timeout - elapsed < (double)DONE_POLL_INTERVAL_MS / 1000.0) {
ms = (int)(1000 * (timeout - elapsed));
if (ms < 1) {
errno = ETIMEDOUT;
return 0;
}
}
}
/* Negative timeout values means no timeout check,
and ms retains its initialized value. */
/* Another done check; it's cheap. */
if (done) {
errno = 0;
return EINTR;
}
/* Wait for input, but not longer than ms milliseconds. */
fds[0].fd = in->descriptor;
fds[0].events = POLLIN;
fds[0].revents = 0;
poll(fds, 1, ms);
/* We don't actually care about the result at this point. */
}
/* Never reached. */
}
static inline size_t input_getline(struct input *const in,
char **const dataptr,
size_t *const sizeptr,
const double timeout)
{
return input_getdelim(in, '\n', dataptr, sizeptr, timeout);
}
int main(void)
{
struct input in;
char *line = NULL;
size_t size = 0;
size_t len;
if (install_done(SIGINT) == -1 ||
install_done(SIGHUP) == -1 ||
install_done(SIGTERM) == -1 ||
install_done(SIGUSR1) == -1) {
fprintf(stderr, "Cannot install signal handlers: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
if (input_use(&in, STDIN_FILENO)) {
fprintf(stderr, "BUG in input_use(): %s.\n", strerror(errno));
return EXIT_FAILURE;
}
while (!done) {
/* Wait for input for five seconds. */
len = input_getline(&in, &line, &size, 5000);
if (len > 0) {
/* Remove the newline at end, if any. */
line[strcspn(line, "\n")] = '\0';
printf("Received: \"%s\" (%zu chars)\n", line, len);
fflush(stdout);
continue;
} else
if (errno == 0) {
/* This is the special case: input_getline() returns 0 with
errno == 0 when there is no more input. */
fprintf(stderr, "End of standard input.\n");
return EXIT_SUCCESS;
} else
if (errno == ETIMEDOUT) {
printf("(No input for five seconds.)\n");
fflush(stdout);
} else
if (errno == EINTR) {
/* Break or continue works here, since input_getline() only
returns 0 with errno==EINTR if done==1. */
break;
} else {
fprintf(stderr, "Error reading from standard input: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
}
printf("Signal received; done.\n");
return EXIT_SUCCESS;
}
Save it as e.g. example.c, compile using e.g. gcc -Wall -Wextra -O2 example.c -o example, and run using ./example. Type input and enter to supply lines, or Ctrl+D at the beginning of a line to end input, or Ctrl+C to send the process a SIGINT signal.
Note the compile-time constant DONE_POLL_INTERVAL_MS. If the signal is delivered between a done check and poll(), this is the maximum delay, in milliseconds (1000ths of a second), that the poll may block; and therefore is roughly the maximum delay from receiving the signal and acting upon it.
To make the example more interesting, it also implements a timeout on reading a full line also. The above example prints when it is reached, but that messes up how the user sees the input they're typing. (It does not affect the input.)
This is by no means a perfect example of such functions, but I hope it is a readable one, with the comments explaining the reasoning behind each code block.
Historically we solved this problem by always setting SA_RESTART and calling longjump() to get out of the signal handler when the condition is met.
The standard makes this undefined but I think this does the right thing when stdin is connected to the keyboard. Don't try it with redirected handles. It won't work well. At least you can check for this condition with isatty(0).
If it doesn't work and you are bent on using signals like this, you'll need to abandon scanf() and friends and get all your input using read().
I am writing a simple shell program in c, and need to handle ctrl-c.
If a foreground process is running, I need to terminate it and continue the main shell loop. If not, I need to do nothing but print that the signal was caught.
Below is my code, based on this thread: Catch Ctrl-C in C
void inthandler(int dummy){
signal(dummy, SIG_IGN);
printf("ctrl-c caught\n");
}
and I call signal() right before entering my main loop
int main(int argc, char*argv[]){
signal(SIGINT, inthandler)
while(true){
//main loop
}
}
As of now, I am able to intercept ctrl-c and print my intended message, but any further input results in a segfault.
How can I return to execution of my main loop after I enter inthandler?
Use sigaction(), not signal(), except when setting the disposition to SIG_DFL or SIG_IGN. While signal() is specified in C, and sigaction() POSIX.1, you'll need POSIX to do anything meaningful with signals anyway.
Only use async-signal safe functions in signal handlers. Instead of standard I/O (as declared in <stdio.h>), you can use POSIX low-level I/O (read(), write()) to the underlying file descriptors. You do need to avoid using standard I/O to streams that use those same underlying descriptors, though, or the output may be garbled due to buffering in standard I/O.
If you change the signal disposition in the signal handler to ignored, only the first signal (of each caught type) will be caught.
Consider the following example program:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
/* Helper function: Write a string to a descriptor, keeping errno unchanged.
Returns 0 if success, errno error code if an error occurs. */
static inline int wrs(const int fd, const char *s)
{
/* Invalid descriptor? */
if (fd == -1)
return EBADF;
/* Anything to actually write? */
if (s && *s) {
const int saved_errno = errno;
const char *z = s;
ssize_t n;
int err = 0;
/* Use a loop to find end of s, since strlen() is not async-signal safe. */
while (*z)
z++;
/* Write the string, ignoring EINTR, and allowing short writes. */
while (s < z) {
n = write(fd, s, (size_t)(z - s));
if (n > 0)
s += n;
else
if (n != -1) {
/* This should never occur, so it's an I/O error. */
err = EIO;
break;
} else
if (errno != EINTR) {
/* An actual error occurred. */
err = errno;
break;
}
}
errno = saved_errno;
return err;
} else {
/* Nothing to write. NULL s is silently ignored without error. */
return 0;
}
}
/* Signal handler. Just outputs a line to standard error. */
void catcher(int signum)
{
switch (signum) {
case SIGINT:
wrs(STDERR_FILENO, "Caught INT signal.\n");
return;
default:
wrs(STDERR_FILENO, "Caught a signal.\n");
return;
}
}
/* Helper function to install the signal handler. */
int install_catcher(const int signum)
{
struct sigaction act;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = catcher;
act.sa_flags = SA_RESTART; /* Do not interrupt "slow" functions */
if (sigaction(signum, &act, NULL) == -1)
return -1; /* Failed */
return 0;
}
/* Helper function to remove embedded NUL characters and CRs and LFs,
as well as leading and trailing whitespace. Assumes data[size] is writable. */
size_t clean(char *data, size_t size)
{
char *const end = data + size;
char *src = data;
char *dst = data;
/* Skip leading ASCII whitespace. */
while (src < end && (*src == '\t' || *src == '\n' || *src == '\v' ||
*src == '\f' || *src == '\r' || *src == ' '))
src++;
/* Copy all but NUL, CR, and LF chars. */
while (src < end)
if (*src != '\0' && *src != '\n' && *src != '\r')
*(dst++) = *(src++);
else
src++;
/* Backtrack trailing ASCII whitespace. */
while (dst > data && (dst[-1] == '\t' || dst[-1] == '\n' || dst[-1] == '\v' ||
dst[-1] == '\n' || dst[-1] == '\r' || dst[-1] == ' '))
dst--;
/* Mark end of string. */
*dst = '\0';
/* Return new length. */
return (size_t)(dst - data);
}
int main(void)
{
char *line = NULL;
size_t size = 0;
ssize_t len;
if (install_catcher(SIGINT)) {
fprintf(stderr, "Cannot install signal handler: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Type Ctrl+D, 'exit', or 'quit' on an empty line to exit.\n");
while (1) {
len = getline(&line, &size, stdin);
if (len < 0)
break;
clean(line, len);
printf("Read %zd chars: %s\n", len, line);
if (!strcmp(line, "exit") || !strcmp(line, "quit"))
break;
}
return EXIT_SUCCESS;
}
On most POSIXy systems, Ctrl+C in a pseudoterminal also clears the current line buffer, so pressing it in the middle of interactively supplying a line will discard the line (the data not sent to the process).
Note that the ^C you normally see in pseudoterminals when you press Ctrl+C is a terminal feature, controlled by the ECHO termios setting. That setting also controls whether keypresses in general are echoed on the terminal.
If you add signal(SIGINT, SIG_IGN) to catcher(), just after the wrs() line, only the first Ctrl+C will print "Caught INT signal"; any following Ctrl+C will just discard the the incomplete line.
So, if you type, say, FooCtrl+CBarEnter, you'll see either
Foo^CCaught INT signal.
Bar
Read 4 chars: Bar
or
Foo^CBar
Read 4 chars: Bar
depending on whether the INT signal generated by Ctrl+C is caught by the handler, or ignored, at that point.
To exit, type exit or quit at the start of a line, or immediately after a Ctrl+C.
There are no segmentation faults here, so if your code does generate one, it must be due to a bug in your program.
How can I return to execution of my main loop after I enter inthandler?
Signal delivery interrupts the execution for the duration of executing the signal handler; then, the interrupted code continues executing. So, the strictly correct answer to that question is by returning from the signal handler.
If the signal handler is installed with the SA_RESTART flag set, then the interrupted code should continue as if nothing had happened. If the signal handler is installed without that flag, then interrupting "slow" system calls may return an EINTR error.
The reason errno must be kept unchanged in a signal handler -- and this is a bug many, many programmers overlook -- is that if an operation in the signal handler changes errno, and the signal handler gets invoked right after a system or C library call failed with an error code, the errno seen by the code will be the wrong one! Granted, this is a rare case (the time window where this can occur is tiny for each system or C library call), but it is a real bug that can occur. When it does occur, it is the kind of Heisenbug that causes developers to rip out their hair, run naked in circles, and generally go more crazy than they already are.
Also note that stderr is only used in the code path where installing the signal handler fails, because I wanted to be sure not to mix I/O and POSIX low-level I/O to standard error.
Yeah I know that sounds crazy but that is the only way I can describe it at this point. I’m writing a program for a class that mimics a terminal, in that it takes commands as inputs and executes them. (I’ll put some code below) As you will see, the program holds a history of commands historyArgs so that the user can execute recent commands.
Command history is listed when the user performs Ctrl-C. Recent commands are accessed with the command 'r' (for most recent) and r 'x' (where x is matches the first letter of a command in recent history). When I started implementing the 'r' command, I started getting this segfault. I then reverted all my changes and added one line at a time. I found that adding even primitive variable declaration causes a segfault (int temp = 10;) But this is where it gets stranger. I believe the line that causes a segfault (int temp = 10;) is never accessed. I put printf statements and flush the output at the beginning of the if block to see if the block has been entered, but they don't execute.
setup was provided for us. It takes the user input and puts it in char *args[] i.e. input = ls -a -C, args = {"ls", "-a", "-C", NULL, ... NULL}. I marked the line in main that somehow leads to a segfault.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#define BUFFER_SIZE 50
static char buffer[BUFFER_SIZE];
#define MAX_LINE 80 /* 80 chars per line, per command, should be enough. */
char *historyArgs[10][MAX_LINE/2 + 1];
int historyCount = 0;
int indexOfLatestCommand = 0;
/* the signal handler function */
void handle_SIGINT() {
//write(STDOUT_FILENO,buffer,strlen(buffer));
if(historyCount > 0){
printf("\n%i command(s), printing most recent:\n", historyCount);
int i;
for(i = 0; i < historyCount && i < 10; i++){
printf("%i.] %s ", i+1, historyArgs[i][0]);
//print args
int j = 1;
while(historyArgs[i][j] != NULL){
printf("%s ", historyArgs[i][j]);
j++;
}
printf("\n");
}
}
else{
printf("\nNo recent commands.\n");
}
fflush(stdout);
}
/**
* setup() reads in the next command line, separating it into distinct tokens
* using whitespace as delimiters. setup() sets the args parameter as a
* null-terminated string.
*/
void setup(char inputBuffer[], char *args[],int *background)
{
int length, /* # of characters in the command line */
i, /* loop index for accessing inputBuffer array */
start, /* index where beginning of next command parameter is */
ct; /* index of where to place the next parameter into args[] */
ct = 0;
/* read what the user enters on the command line */
length = read(STDIN_FILENO, inputBuffer, MAX_LINE);
start = -1;
if (length == 0)
//exit(0); /* ^d was entered, end of user command stream */
if (length < 0){
perror("error reading the command");
exit(-1); /* terminate with error code of -1 */
}
/* examine every character in the inputBuffer */
for (i = 0; i < length; i++) {
switch (inputBuffer[i]){
case ' ':
case '\t' : /* argument separators */
if(start != -1){
args[ct] = &inputBuffer[start]; /* set up pointer */
ct++;
}
inputBuffer[i] = '\0'; /* add a null char; make a C string */
start = -1;
break;
case '\n': /* should be the final char examined */
if (start != -1){
args[ct] = &inputBuffer[start];
ct++;
}
inputBuffer[i] = '\0';
args[ct] = NULL; /* no more arguments to this command */
break;
case '&':
*background = 1;
inputBuffer[i] = '\0';
break;
default : /* some other character */
if (start == -1)
start = i;
}
}
args[ct] = NULL; /* just in case the input line was > 80 */
}
int main(void)
{
int i;
char inputBuffer[MAX_LINE]; /* buffer to hold the command entered */
int background; /* equals 1 if a command is followed by '&' */
char* args[MAX_LINE/2+1];/* command line (of 80) has max of 40 arguments */
int status;
struct sigaction handler;
handler.sa_handler = handle_SIGINT;
sigaction(SIGINT, &handler, NULL);
strcpy(buffer,"Caught <ctrl><c>\n");
while (1){ /* Program terminates normally inside setup */
background = 0;
printf("COMMAND->");
fflush(0);
setup(inputBuffer, args, &background); /* get next command */
//If command wasn't empty
if(args[0] != NULL){
if(strcmp(args[0], "r") != 0){
//Copy into history if not a recent call
for(i = 0; i < MAX_LINE/2+1 && args[i] != NULL; i++){
historyArgs[historyCount%10][i] = malloc(strlen(args[i]));
strcpy(historyArgs[historyCount%10][i], args[i]);
}
indexOfLatestCommand = historyCount%10;
historyCount++;
}
//Create child process
int pid = fork();
//In child process
if(pid == 0){
if(strcmp(args[0], "r") == 0){
//If only "r" was entered, execute most recent command
if(args[1] == NULL){
printf("Entering recent?\n");
fflush(stdout);
int temp = 10; //SEGFAULTS HERE IF THIS IS INCLUDED
execvp(historyArgs[indexOfLatestCommand][0], &historyArgs[indexOfLatestCommand][0]);
}
else{
//Find in args[1][0] history, run if found
for(i = indexOfLatestCommand; i >= 0; i--){
if(historyArgs[i][0][0] == args[1][0]){
execvp(historyArgs[i][0], &historyArgs[i][0]);
break;
}
}
if(i == -1){
for(i = historyCount > HISTORY_SIZE ? HISTORY_SIZE : historyCount; i > indexOfLatestCommand; i--){
if(historyArgs[i][0][0] == args[1][0])
execvp(historyArgs[i][0], &historyArgs[i][0]);
break;
}
}
}
}
else execvp(args[0], &args[0]);
}
//In parent process
else if (pid > 0){
/*If child isn't a background process,
wait for child to terminate*/
if(background == 0)
while(wait(&status) != pid);
}
}
}
}
Another thing worth mentioning is that declaring a variable in that spot doesn't cause a segfault. Only assigning a value to a new variable does. Reassigning globals in that section also doesn't cause a segfault.
EDIT: What triggers a crash. Commands execute correctly. When you run it, you can type in any command, and that should work. It isn't until I perform Ctrl-C and print out the history that the program segfaults.
Example input:
ls
ls -a
grep
Ctrl-C
HEADS UP: if you decide to run this, know that to end the task, you will probably need to use the kill command because I haven't implement "q" to quit.
Symptoms like you see (unrelated code changes appear to affect the nature of a crash) usually mean that your program caused undefined behaviour earlier. The nature of the behaviour changes because your program is relying on garbage values it has read or written at some stage.
To debug it, try and remove all sources of undefined behaviour in your program. The most obvious one is the content of your void handle_SIGINT() function. The only things you can portably do in a signaler are:
Set a variable of type volatile sig_atomic_t, or other lock-free type, and return
Do other stuff and call _Exit, abort or similar.
Especially, you cannot call any library functions as they may not be re-entrant.
For a full specification see section 7.14.1 of the current C Standard. If you are also following some other standard, e.g. POSIX, it may specify some other things which are permitted in a signal handler.
If you do not intend to exit then you must set a flag , and then test that flag from your main "thread" later to see if a signal arose.
I wrote a C application for a socialization network and also a simple room-based chat. I used ncurses, sockets and basic networking stuff.
The problem is that my function uses select() to read from server socket AND stdin so when I start to write a message, the output window freezes and only shows messages from other clients after I hit enter.
I tried everything possible .. Is there a way to fix this ?
I also tried to force nocbreak().It works okay but if I do that, when I write the message, the echoing is disabled and nothing shows up in the input window as I type, even though the message is there but like "invisible".
Here is the code :
ssize_t safePrefRead(int sock, void *buffer)
{
size_t length = strlen(buffer);
ssize_t nbytesR = read(sock, &length, sizeof(size_t));
if (nbytesR == -1)
{
perror("read() error for length ! Exiting !\n");
exit(EXIT_FAILURE);
}
nbytesR = read(sock, buffer, length);
if (nbytesR == -1)
{
perror("read() error for data ! Exiting !\n");
exit(EXIT_FAILURE);
}
return nbytesR;
}
ssize_t safePrefWrite(int sock, const void *buffer)
{
size_t length = strlen(buffer);
ssize_t nbytesW = write(sock, &length, sizeof(size_t));
if (nbytesW == -1)
{
perror("write() error for length ! Exiting !\n");
exit(EXIT_FAILURE);
}
nbytesW = write(sock, buffer, length);
if (nbytesW == -1)
{
perror("write() error for data ! Exiting !\n");
exit(EXIT_FAILURE);
}
return nbytesW;
}
void activeChat(int sC, const char *currentUser, const char *room)
{
char inMesg[513], outMesg[513];
char user[33];
int winrows, wincols;
WINDOW *winput, *woutput;
initscr();
nocbreak();
getmaxyx(stdscr, winrows, wincols);
winput = newwin(1, wincols, winrows - 1, 0);
woutput = newwin(winrows - 1, wincols, 0, 0);
keypad(winput, true);
scrollok(woutput, true);
wrefresh(woutput);
wrefresh(winput);
fd_set all;
fd_set read_fds;
FD_ZERO(&all);
FD_ZERO(&read_fds);
FD_SET(0, &all);
FD_SET(sC, &all);
wprintw(woutput, "Welcome to room '%s' \n Use /quitChat to exit !\n!", room);
wrefresh(woutput);
while (true)
{
memcpy( &read_fds, &all, sizeof read_fds );
if (select(sC + 1, &read_fds, NULL, NULL, NULL) == -1)
{
perror("select() error or forced exit !\n");
break;
}
if (FD_ISSET(sC, &read_fds))
{
memset(inMesg, 0, 513);
safePrefRead(sC, user);
safePrefRead(sC, inMesg);
wprintw(woutput, "%s : %s\n", user, inMesg);
wrefresh(woutput);
wrefresh(winput);
}
if (FD_ISSET(0, &read_fds))
{
//wgetnstr(winput, "%s", outMesg);
int a, i = 0;
while ( i < MAX_BUF_LEN && (a = wgetch(winput)) != '\n')
{
outMesg[i] = (char)a;
i++;
}
outMesg[i] = 0;
if (outMesg[0] == 0)
continue;
if (strcmp(outMesg, "/quitChat") == 0)
{
safePrefWrite(sC, outMesg);
break;
}
safePrefWrite(sC, outMesg);
delwin(winput);
winput = newwin(1, wincols, winrows - 1, 0);
keypad(winput, true);
wrefresh(winput);
}
}
delwin(winput);
delwin(woutput);
endwin();
}
-safePrefWrite and safePrefRead are wrappers for prexied read / write and error treating
-sC is the server socket.
LE: I tried using fork and threads. Using fork was behaving the same and threads were a disaster, the terminal was messed up.
Thank you.
modify the while(true) loop to only handle one char at a time for the stdin.
Which mostly means for stdin, read a single char:
if char is '\n' then handle as currently,
otherwise, just append char to the buffer to write.
Always, before appending a char to buffer to write, check that buffer is not full.
add code to handle the case where the buffer to write is full
end the function with this sequence:
delwin(winput);
delwin(woutput);
endwin();
endwin();
to end both windows.
Do not call endwin() during processing of the socket input.
Do not call endwin() when select() returns an error condition
the fd_set is not an intrinsic size in C, so use memcpy() to set
read_fds from all. suggest:
memcpy( &read_fds, &all, sizeof read_fds );
the parameter: currentUser is not used, suggest inserting the line:
(void)currentUser;
to eliminate a compiler warning message.
for readability, and ease of understandability, suggest #define the magic numbers 513 and 33 with meaningful names, then use those meaningful names throughout the code.
#define MAX_BUF_LEN (513)
#define MAX_USER_LEN (33)
this line: outMesg[i] = a; raises a compiler warning, suggest:
outMesg[i] = (char)a;
This line: while ( (a = wgetch(winput)) != '\n') can allow the buffer outMesg[] to be overrun, resulting in undefined behaviour and can lead to a seg fault event. suggest:
while ( i < MAX_BUF_LEN && (a = wgetch(winput)) != '\n')
Suggest posting the prototypes for the safePrefWrite() and safePrefRead() functions, similar to:
void safePrefRead( int, char * );
void safePrefWrite( int, char * );
As noted by #user3629249, there are several criticisms which can be applied to the sample code. However, OP's question is not addressed by those improvements.
OP seems to have overlooked these functions:
cbreak or raw, to make wgetch read unbuffered data, i.e., not waiting for '\n'.
nodelay or timeout, to control the amount of time wgetch spends waiting for input.
By the way, making select work with a curses program will make assumptions about the curses library internal behavior: getting that to work reliably can be troublesome.
Fixed it finally by using only the big loop.
Here is the code if anyone has the same problem in the future :
if (FD_ISSET(0, &read_fds))
{
inChar = wgetch(winput);
if (inChar == 27)
{
safePrefWrite(sC, "/quit");
break;
}
if (inChar == KEY_UP || inChar == KEY_DOWN || inChar == KEY_LEFT || inChar == KEY_RIGHT)
continue;
if (inChar == KEY_BACKSPACE || inChar == KEY_DC || inChar == 127)
{
wdelch(winput);
wrefresh(winput);
if (i != 0)
{
outMesg[i - 1] = 0;
i--;
}
}
else
{
outMesg[i] = (char)inChar;
i++;
}
if (outMesg[i - 1] == '\n')
{
outMesg[i - 1] = 0;
i = 0;
if (outMesg[0] == 0)
continue;
if (strcmp(outMesg, "/quit") == 0)
{
safePrefWrite(sC, outMesg);
break;
}
safePrefWrite(sC, outMesg);
delwin(winput);
winput = newwin(1, wincols, winrows - 1, 0);
keypad(winput, true);
wrefresh(winput);
memset(outMesg, 0, 513);
}
}
I also use raw() to disable signals and to treat the codes how I want.
Anything else above and below this "if" is just like in the 1st post.
Am I not leaving my signal handler function in the correct way? It does not seem to return to the program normally. Instead it goes into the loop and where it should wait for user input, it skips and reads the length of the "user input" to -1 and errors out. (Will make more sense in code.)
void handle_SIGINT() {
int k = recent;
int count = 0;
int stop;
if (stringSize >= 10) {
stop = 10;
}
else {
stop = p;
}
printf("\nCommand History:\n");
for (count = 0; count < stop; count++) {
if (k < 0) {
k += 10;
}
printf("%s", string[abs(k)]);
k -= 1;
}
}
void setup(char inputBuffer[], char *args[],int *background)
{
//char inputBuffer[MAX_LINE];
int length, /* # of characters in the command line */
i, /* loop index for accessing inputBuffer array */
start, /* index where beginning of next command parameter is */
ct; /* index of where to place the next parameter into args[] */
int add = 1;
ct = 0;
/* read what the user enters on the command line */
length = read(STDIN_FILENO, inputBuffer, MAX_LINE);
printf("%i",length);
start = -1;
if (length == 0)
exit(0); /* ^d was entered, end of user command stream */
if (length < 0){
perror("error reading the commanddddddddd");
exit(-1); /* terminate with error code of -1 */
}
}
int main(void)
{
char inputBuffer[MAX_LINE]; /* buffer to hold the command entered */
int background; /* equals 1 if a command is followed by '&' */
char *args[MAX_LINE/2+1];/* command line (of 80) has max of 40 arguments */
FILE *inFile = fopen("pateljay.history", "r");
if (inFile != NULL) {
int count = 0;
char line[MAX_LINE];
while (fgets(line,sizeof line, inFile) != NULL) {
string[count] = strdup(line);
//string[count][strlen(line)] = '\n';
//string[count][strlen(line) + 1] = '\0';
printf("%s", string[count]);
count++;
stringSize++;
}
p = count % 10;
recent = abs(p - 1);
}
fclose(inFile);
/* set up the signal handler */
struct sigaction handler;
handler.sa_handler = handle_SIGINT;
sigaction(SIGINT, &handler, NULL);
while (1) {/* Program terminates normally inside setup */
background = 0;
printf("COMMAND->");
fflush(0);
setup(inputBuffer, args, &background);/* get next command */
}
}
So when ctrl+c is entered it should catch the signal and handle it. Once it returns back to main, it goes into setup and completely skips the read function and makes length equal to -1. This in turn errors out the program. I think the code inside handle_SIGINT is irrelevant as it is right now. Does anyone know any reason why it would be skipping the read function in setup?
read is blocking, waiting for input. SIGINT arrives. The kernel calls your signal handler. When your signal handler returns, the kernel makes read return -1 and set errno to EINTR. You need to check for this case and handle it by calling read again:
do {
length = read(STDIN_FILENO, inputBuffer, MAX_LINE);
} while (length == -1 && errno == EINTR);
The signal handler is supposed to take an int argument:
void handle_sigint(int signum) {}