How to use _popen function run python and get data back

I want to achieve my own remote login shell using c. In the section of command execution , I use _popen and fgets function to communicate with cmd, In the most conditions ,the program runs good. However when I input something like "python2" or "notepad", the program got stuck, I guess that's caused by gets. I wonder how to process this problem. How does the famous program like ssh or telnet deal with that?

I put my code below.

//cmd is the command will be processed, result is where the return data stored
int execmd(char* cmd,char* result) {
    char buffer[128];                                              
    FILE* pipe = _popen(cmd, "r");            
    if (!pipe) return 0;   
                  
    int i = 0;
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe)){            
            printf("%s\n",buffer);
            strcat(result,buffer);
        }
        i++;
    }
    i = i*128;
    _pclose(pipe);                            
    return i;                                 
}