Hiren Pandya
Hiren Pandya

Reputation: 995

While loop not continuing, exits after 1 iteration

Here is my code where I am trying to change one value and 3x3 matrix and then automatically changing all the elements of the matrix one by one. My problem is, while loop mentioned in the program should continue infinitely but it is not. It is exiting after one iteration. I've tried gdb but it is not showing any relevant information regarding this problem..

Code:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

int matrix[3][3] = {0};
int row=0;
int col=0;
int i, j, k, l;
int seccount = 0;

char buffer[4096];
//buffer[0] = '\0';
void value_changer();
static void catch_signal(int signal)
{
    printf("*********************** Seconds : %d ******************************\n", seccount++);
    printf(buffer);
    puts("Second completes");
}

void value_changer(void)
{
    char temp[32];
    buffer[0] = '\0';
    matrix[0][0] += 1;
    for (int i = 0; i < sizeof(matrix) / sizeof(matrix[0]); i++)
    {
        for (int j = 0; j < sizeof(matrix/*[i]*/) / sizeof(matrix/*[i]*/[0]); j++)
        {
            if(i==0 && j==0)
            {
                for (int k = 0; k < sizeof(matrix) / sizeof(matrix[0]); k++)
                {
                    for (int l = 0; l < sizeof(matrix/*[k]*/) / sizeof(matrix/*[k]*/[0]); l++)
                    {

                        snprintf(temp, sizeof(temp) - 1, "%d ", matrix[k][l]);
                        strcat(buffer, temp);
                    }
                    strcat(buffer, "\n");
                }
                strcat(buffer, "\n");
            }
        }
    }
    //raise(SIGINT);
}

int main()
{
    if (signal(SIGINT, catch_signal) == SIG_ERR)
    {
        fputs("An error occurred while setting a signal handler.\n", stderr);
        return EXIT_FAILURE;
    }
    //buffer[0] = '\0';
    while(1) // I want to continue the loop infinite time.
    {
        value_changer();
        raise(SIGINT);
        sleep(1); // This is to make sure that the each output is separated by 1 second delay.
    }
    return 0;
}

Without giving me any error, it exits after one iteration.

GDB shows:

Starting program: /home/sujal.p/signal/test

Program received signal SIGINT, Interrupt.
0x00130416 in __kernel_vsyscall ()
(gdb)

Upvotes: 1

Views: 232

Answers (1)

P.P
P.P

Reputation: 121347

It depends on how signal() works on your system. I guess on your platform after the first SIGINT, the default signal action SIG_DFL is restored which causes the program to terminate the next time. One option is to restore the handler everytime. Or better option would be to use sigaction().

Note: You shouldn't call printf from inside the signal handler (or any non reentrant function for that matter).

Upvotes: 3

Related Questions