This comes from one of my own projects, Apache 2.0 licensed. It was experiments I did for this exact issue: https://github.com/tan-ce/pts-multi/blob/master/jni/helpers.c#L288

The code was written mostly based off the man pages by myself, not copied wholesale from anywhere. At worst, I might have copied some lines off some example code.