Signal Handling and Context Switches


 
Thread Tools Search this Thread
Top Forums Programming Signal Handling and Context Switches
# 8  
Old 11-26-2008
I don't think it's a good idea to call swapcontext() by main() even indirectly, main is special in many ways that most threads aren't. What happens when you call swapcontext() from a third thread instead?
# 9  
Old 11-26-2008
Why did you pick 65536 instead of SIGSTKSZ for stack size?
# 10  
Old 11-27-2008
Are you overflowing the signal stack?
# 11  
Old 11-27-2008
You are blowing the stack somewhere, I don't see context referencing either.
Here is the standard POSIX example for this -- note the use of static functions and some other context setups you do not seem to have:
Code:
#include <stdio.h>
#include <ucontext.h>

static ucontext_t ctx[3];

static void
f1 (void)
{
    puts("start f1");
    swapcontext(&ctx[1], &ctx[2]);
    puts("finish f1");
}

static void
f2 (void)
{
    puts("start f2");
    swapcontext(&ctx[2], &ctx[1]);
    puts("finish f2");
}

int
main (void)
{
    char st1[8192];
    char st2[8192];

    getcontext(&ctx[1]);
    ctx[1].uc_stack.ss_sp = st1;
    ctx[1].uc_stack.ss_size = sizeof st1;
    ctx[1].uc_link = &ctx[0];
    makecontext(&ctx[1], f1, 0);

    getcontext(&ctx[2]);
    ctx[2].uc_stack.ss_sp = st2;
    ctx[2].uc_stack.ss_size = sizeof st2;
    ctx[2].uc_link = &ctx[1];
    makecontext(&ctx[2], f2, 0);

    swapcontext(&ctx[0], &ctx[2]);
    return 0;
}

# 12  
Old 11-27-2008
Note corona688's comment - the only swpcontext call in main above is one to set context to a function, rather than calling it. main is not swapping context repeatedly.
# 13  
Old 12-01-2008
Sorry for the late reaction, I wasn't online during the holidays.
@jim mcnamara: How can I detect whether I am overflowing the signal stack or not? And what do you mean with context referencing? I've changed the stack size from 65365 to 4096. But it doesn't have any effects.

Btw. I found a code sample which is similar to my problem. But this example seems to work. The code is in the listing below (source: CIS381 - Fall 2008). The important functions are scheduler() and timer_interrupt().
Code:
#include <ucontext.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <poll.h>

/* ucontext sample program

   by Jon Kaplan and Robert Spier (October 24th, 1999)
   Updated for 2000 and poll, Robert Spier
   sigprocmask gaff fixed by Ben Slusky
   ported to Linux by Eric Cronin
   
   Demonstrates swapping between multiple processor contexts (in a
   _stable_ way).  n-1 contexts do nothing.  1 context accepts input
   and outputs it.
*/


#define NUMCONTEXTS 10              /* how many contexts to make */
#define STACKSIZE 4096              /* stack size */
#define INTERVAL 100                /* timer interval in nanoseconds */

ucontext_t signal_context;          /* the interrupt context */
void *signal_stack;                 /* global interrupt stack */

ucontext_t contexts[NUMCONTEXTS];   /* store our context info */
int curcontext = 0;                 /* whats the current context? */
ucontext_t *cur_context;            /* a pointer to the current_context */

/* The scheduling algorithm; selects the next context to run, then starts it. */
void
scheduler()
{
    printf("scheduling out thread %d\n", curcontext);

    curcontext = (curcontext + 1) % NUMCONTEXTS; /* round robin */
    cur_context = &contexts[curcontext];

    printf("scheduling in thread %d\n", curcontext);

    setcontext(cur_context); /* go */
}

/*
  Timer interrupt handler.
  Creates a new context to run the scheduler in, masks signals, then swaps
  contexts saving the previously executing thread and jumping to the
  scheduler.
*/
void
timer_interrupt(int j, siginfo_t *si, void *old_context)
{
    /* Create new scheduler context */
    getcontext(&signal_context);
    signal_context.uc_stack.ss_sp = signal_stack;
    signal_context.uc_stack.ss_size = STACKSIZE;
    signal_context.uc_stack.ss_flags = 0;
    sigemptyset(&signal_context.uc_sigmask);
    makecontext(&signal_context, scheduler, 0);

    /* save running thread, jump to scheduler */
    swapcontext(cur_context,&signal_context);
}

/* Set up SIGALRM signal handler */
void
setup_signals(void)
{
    struct sigaction act;

    act.sa_sigaction = timer_interrupt;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_RESTART | SA_SIGINFO;

    if(sigaction(SIGALRM, &act, NULL) != 0) {
        perror("Signal handler");
    }
}


/* Thread bodies */
void
thread1()
{
    while(1) {
        poll(NULL,0,100);
    };     /* do nothing nicely */
}

void
thread2()
{
    char buf[1024];
    /* get a string.. print a string.. ad infinitum */
    while(1) {
        fgets(buf, 1024, stdin);
        printf("[[[[[[%s]]]]]]\n",buf);
    }
}

/* helper function to create a context.
   initialize the context from the current context, setup the new
   stack, signal mask, and tell it which function to call.
*/
void
mkcontext(ucontext_t *uc,  void *function)
{
    void * stack;

    getcontext(uc);

    stack = malloc(STACKSIZE);
    if (stack == NULL) {
        perror("malloc");
        exit(1);
    }
    /* we need to initialize the ucontext structure, give it a stack,
        flags, and a sigmask */
    uc->uc_stack.ss_sp = stack;
    uc->uc_stack.ss_size = STACKSIZE;
    uc->uc_stack.ss_flags = 0;
    sigemptyset(&uc->uc_sigmask);

    /* setup the function we're going to, and n-1 arguments. */
    makecontext(uc, (void(*)())function, 0);

    printf("context is %x\n",(unsigned int)uc);
}


int
main()
{
    int i;
    struct itimerval it;

    fprintf(stderr,"Process Id: %d\n", (int)getpid());

    /* allocate the global signal/interrupt stack */
    signal_stack = malloc(STACKSIZE);
    if (signal_stack == NULL) {
        perror("malloc");
        exit(1);
    }

    /* make all our contexts */
    mkcontext(&contexts[0], (void*)thread2);
    for(i=1; i < NUMCONTEXTS; i++)
        mkcontext(&contexts[i], (void*)thread1);


    /* initialize the signal handlers */
    setup_signals();

    /* setup our timer */
    it.it_interval.tv_sec = 0;
    it.it_interval.tv_usec = INTERVAL * 1000;
    it.it_value = it.it_interval;
    if (setitimer(ITIMER_REAL, &it, NULL) ) perror("setitiimer");

    /* force a swap to the first context */
    cur_context = &contexts[0];
    setcontext(&contexts[0]);

    return 0; /* make gcc happy */
}

But I stumbled upon the swapcontext in the signal handler. I thought it isn't a good idea to use it in the signal handling method. That's why it is also hard to say, what happens after swapping back into the signal handler? Is anyone able to explain this code snippet?
# 14  
Old 12-02-2008
Concerning my concrete problem I found out that the segmentation fault occurs while calling swapcontext() in the while-loop of scheduler_function(). I also tried to run the program without using an alternate stack with no effects to the behaviour.
Another interesting fact is, that the segmenation fault does not occur, when I set the size of the stacks, which will be used in the contexts, to 65536. But than, the counting does not work in every case, too.

Last edited by XComp; 12-02-2008 at 07:29 PM.. Reason: additional information
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

problem in reforking and signal handling

hi friends i have a problem in signal handling ... let me explain my problem clearly.. i have four process .. main process forks two child process and each child process again forks another new process respectively... the problem is whenever i kill the child process it is reforking and the... (2 Replies)
Discussion started by: senvenugopal
2 Replies

2. UNIX and Linux Applications

SIGSEGV Signal handling

Hello, Can anybody tell me how can i handle segmentation fault signal, in C code? (2 Replies)
Discussion started by: mustus
2 Replies

3. Programming

problem in SIGSEGV signal handling

i wrote handler for sigsegv such that i can allocate memory for a variable to which sigsegv generated for illlegal acces of memory. my code is #include <signal.h> #include<stdio.h> #include<stdlib.h> #include<string.h> char *j; void segv_handler(int dummy) { j=(char *)malloc(10); ... (4 Replies)
Discussion started by: pavan6754
4 Replies

4. Programming

Signal handling

I am trying to write a small program where I can send signals and then ask for an action to be triggered if that signal is received. For example, here is an example where I am trying to write a programme that will say you pressed ctrl*c when someone presses ctrl+c. My questions are what you would... (1 Reply)
Discussion started by: #moveon
1 Replies

5. Programming

signal handling question

Hello all, I am starting to learn signal handling in Linux and have been trying out some simple codes to deal with SIGALRM. The code shown below sets a timer to count down. When the timer is finished a SIGALRM is produced. The handler for the signal just increments a variable called count. This... (7 Replies)
Discussion started by: fox_hound_33
7 Replies

6. UNIX for Advanced & Expert Users

thread context switches: detection, prevention

#1: does anyone know how to detect how many times (and/or the time length) a given thread has been context switched out of the CPU? #2: are there any tchniques that minimize/eliminate your thread getting context switched? I would be happy to know the answers to these questions for ANY... (2 Replies)
Discussion started by: fabulous2
2 Replies

7. Shell Programming and Scripting

Signal handling in Perl

Guys, I'm doing signal handling in Perl. I'm trying to catch ^C signal inside the script. There two scripts : one shell script and one perl script. The shell script calls the perl script. For e.g. shell script a.sh and perl scipt sig.pl. Shell script a.sh looks something like this :... (6 Replies)
Discussion started by: obelix
6 Replies

8. Programming

Signal Handling

Hi folks I'm trying to write a signal handler (in c on HPUX) that will catch the child process launched by execl when it's finished so that I can check a compliance file. The signal handler appears to catch the child process terminating however when the signal handler completes the parent... (3 Replies)
Discussion started by: themezzaman
3 Replies

9. UNIX for Advanced & Expert Users

signal handling in shell script

Hi can any please tell me is it possible to catch the signal in a shell script like we do in C. if yes please give me some idea or a link. (4 Replies)
Discussion started by: Raom
4 Replies

10. UNIX for Advanced & Expert Users

Handling SIGUSR2 signal

HI, I need to handle SIGUSR2 signal in my application to change the state of the application dynamically. I have implemented the signal handler. However the application is able to catch only one SIGUSR2 signal. The second SIGUSR2 signal causes the application to crash. This is happning only with... (3 Replies)
Discussion started by: diganta
3 Replies
Login or Register to Ask a Question