justincormack / ljsyscall

LuaJIT Unix syscall FFI
http://www.myriabit.com/ljsyscall/
Other
440 stars 54 forks source link

linux/types: Add __len metamethod for cpu_set_t #185

Closed lukego closed 9 years ago

lukego commented 9 years ago

This makes the '#' operator return the number of elements in a cpu_set_t object. Originally the return value was always 128 based on the size of the structure rather than the number of elements set.

This change is immediately useful for some code of mine that depends on having affinity to one CPU core and wants to run:

assert(#S.sched_getaffinity() == 1, "must be locked to one core")

Summary of original behavior:

grindelwald$ sudo rlwrap ./snabb snsh -i
Snabb> S=require("syscall")
Snabb> =S.sched_getaffinity()
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47}
Snabb> =#S.sched_getaffinity()
128
Snabb> S.sched_setaffinity(0, {0,1})
Snabb> =#S.sched_getaffinity()
128

and new behavior:

grindelwald$ sudo rlwrap ./snabb snsh -i
Snabb> S=require("syscall")
Snabb> =S.sched_getaffinity()
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47}
Snabb> =#S.sched_getaffinity()
48
Snabb> S.sched_setaffinity(0, {0,1})
Snabb> =#S.sched_getaffinity()
2
lukego commented 9 years ago

On reflection it would be really nice to be able to treat a CPU set like an array e.g. count its elements, iterate over its elements, access its first element, etc. Perhaps a better solution would be to convert the cpu_set_t into an array? (Even for sched_getaffinity() to do that automatically for its return value?)

justincormack commented 9 years ago

The thing to do would be to return an array from get unless the user actually passes a cpu_set_t - in which case return that. That's the fairly standard arrangement elsewhere. The set syscall should accept either. Then most people can just use arrays but if you want to interoperate with something else that uses the type you can.

lukego commented 9 years ago

Good idea. Closing for now. I opened this a little prematurely because I haven't fleshed out my use case yet.