1

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)
4

1 回答 1

3

这取决于 signal() 在您的系统上的工作方式。我猜在第一个 SIGINT 之后在您的平台上,默认信号操作 SIG_DFL 会恢复,这会导致程序下次终止。一种选择是每次都恢复处理程序。或者更好的选择是使用 sigaction()。

注意:您不应该从信号处理程序(或任何非可重入函数)内部调用 printf。

于 2013-04-17T12:49:06.857 回答