undefinedfix
Sign in

Wenti encountered in C + + / C < ucontext. H > co program debugging

DHa edited in Tue, 22 Nov 2022

Today, I use the functions under < ucontext. H > to try to do coprogramming. But I found a strange phenomenon.

#include<iostream>
#include<ucontext.h>
#include<unistd.h>
using namespace std;

void function(){
    cout<<"run this"<<endl;
    //sleep(1);
    return;
}

void function2(){
    cout<<"I am yuhaoxiao."<<endl;
    return;
}

int main(){
    cout<<"in main"<<endl;
    char stack[1024],stack2[1024];
    ucontext_t main,other,func;
    getcontext(&main);

    getcontext(&func);

    func.uc_stack.ss_sp=stack2;
    func.uc_stack.ss_size=sizeof(stack2);
    func.uc_stack.ss_flags=0;
    func.uc_link=&other;

    makecontext(&func,function2,0);

    main.uc_stack.ss_sp=stack;
    main.uc_stack.ss_size=sizeof(stack);
    main.uc_stack.ss_flags=0;
    main.uc_link=&func;
    
    makecontext(&main,function,0);
    cout<<"test flag 1"<<endl;
    swapcontext(&other,&main);
    //setcontext(&main);
    cout<<"in main"<<endl;
    return 0;
}

Debug code as above. In the above code, the segmentation fault will appear when the function () is run with sleep (1), but it can run successfully without sleep (1). I would like to ask you what is the reason for the great God.

2 Replies
Heneer
commented on Wed, 23 Nov 2022

I compile and run this program without segment fault? I'll remove the sleep comment in function from the code you pasted. It's no problem to compile and run. g++ :g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

In addition, your program is a bit messy, jump is not very intuitive, variable naming in the program is also a bit random, you can't see the name to know the meaning. Can refer to my collection of a note, relatively clear. Implementation of coroutine-c language

If you find any problem, you can comment and let me know. I didn't run segment fault here

M_Salehi
commented on Wed, 23 Nov 2022

Stack is too small. It takes more than 1000 bytes of stack space to call sleep (1).