返回资讯中心
外部精选
软件工程
#开发者实时流

A hacky f*d up way to portably access errno from outside of C

(in practice i can't imagine any reason SEEK_SET wouldn't be 0, but unnecessary fucked up hacks are fun so for now let's just pretend that any of this actually matters)

Hacker News 最新dverlaeckt802026/10/25 · 19 天前2 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

.

(in practice i can't imagine any reason SEEK_SET wouldn't be 0, but unnecessary fucked up hacks are fun so for now let's just pretend that any of this actually matters)

it's actually possible to work around this! lseek returns the new offset after seeking. so we can call lseek with an arbitrary whence value, and use the return value to determine whether it did what we wanted. if not, just repeat with different whence values until it works!

let i = 0; for (i <= 2; i += 1) { if (c_lseek(STDERR_FILENO, 0, i) == 0) { break; }; }; assert(i <= 2); defer c_lseek(STDERR_FILENO, 0, i);

i just loop from 0 to 2, because i figure that it'll probably always be one of those values. but there's no reason higher values couldn't also be checked.

conclusion

export fn main() void = { // demonstration: pass in -1 as the fd to cause EBADF match (write(-1, &0u8, 1)) { case size => abort(

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →