Skip to content

Instantly share code, notes, and snippets.

@aravindavk
Created June 30, 2020 17:23
Show Gist options
  • Save aravindavk/a2d6ac25427d0362babb551f67a53425 to your computer and use it in GitHub Desktop.
Save aravindavk/a2d6ac25427d0362babb551f67a53425 to your computer and use it in GitHub Desktop.
Missing Errnos - Crystal lang
# Run this using
# touch sample.txt
# crystal run missing_errnos.cr -- sample.txt
# Above command fails to compile if we uncomment the line 39
lib LibXAttr
{% if flag?(:linux) %}
fun getxattr(path : LibC::Char*, name : LibC::Char*, value : LibC::Char*, size : LibC::SizeT) : LibC::Int
{% end %}
{% if flag?(:darwin) %}
fun getxattr(path : LibC::Char*, name : LibC::Char*, value : LibC::Char*, size : LibC::SizeT, position : LibC::UInt32T, options : LibC::Int) : LibC::Int
{% end %}
end
def getxattr(path, key, value, size)
{% if flag?(:linux) %}
LibXAttr.getxattr(path, key, value, size)
{% end %}
{% if flag?(:darwin) %}
LibXAttr.getxattr(path, key, value, size, 0, 0)
{% end %}
end
def raise_error()
raise IO::Error.from_errno("Xattr Error")
end
begin
size = getxattr(ARGV[0], "user.nonexisting", nil, 0)
raise_error() if size == -1
ptr = Slice(LibC::Char).new(size)
res = getxattr(ARGV[0], "user.nonexisting", ptr, size)
raise_error() if res == -1
puts String.new(ptr)
rescue ex: IO::Error
# Uncommenting below line raises error on Mac
# if ex.os_error == Errno::ENODATA || ex.os_error == Errno::ENOATTR
if ex.os_error == Errno::ENODATA
puts "Xattr not found"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment