Skip to content

golang 基于信号实现抢占式调度基本原理 #16

Description

@hustxiaoc
#define _GNU_SOURCE 1
#include<iostream>
#include<iomanip>
#include<signal.h>
#include <ucontext.h>
#include <unistd.h>

using std::cout;


static void test() {
    cout << "call test function" << std::endl;
}

static volatile int runing = 1;

static void handler(int, siginfo_t *si, void *ptr) {
    ucontext_t *uc = (ucontext_t *)ptr;
    cout << "ip: 0x" << std::hex << uc->uc_mcontext.gregs[REG_RIP] << '\n';
    greg_t sp = uc->uc_mcontext.gregs[REG_RSP];
    sp = sp - 8;
    *((greg_t*)sp) = uc->uc_mcontext.gregs[REG_RIP];
    uc->uc_mcontext.gregs[REG_RIP] = (greg_t)&test;
    uc->uc_mcontext.gregs[REG_RSP] = sp;
    runing = 0;
}

int main()
{
begin:
    cout.setf(std::ios::unitbuf);
    cout << getpid() <<  " ," <<  &&begin << " ~ " << &&before << " ~ " << &&after << '\n';

    struct sigaction s;
    s.sa_flags = SA_SIGINFO|SA_RESETHAND;
    s.sa_sigaction = handler;
    sigemptyset(&s.sa_mask);
    sigaction(SIGUSR1, &s, 0);

    int i = 0;
before:
    do
    {
        i++;
    } while (runing);
    
    cout << "after loop" << std::endl;
after:
    cout << "End.\n";
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions