Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hustxiaoc opened this issue Apr 27, 2022 · 1 comment
Open

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

hustxiaoc opened this issue Apr 27, 2022 · 1 comment

Comments

@hustxiaoc
Copy link
Owner

#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";
}
@hustxiaoc
Copy link
Owner Author

hustxiaoc commented Apr 27, 2022

output

21031 ,0x564298dcc40b ~ 0x564298dcc4e1 ~ 0x564298dcc521
si:0x3e800004e9a
ip: 0x564298dcc4e8
call test function
after loop
End.

使用 kill -USR1 21031 发送信号

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant