Expand description
Execute system call directly without std or libc.
Usage
Add this to Cargo.toml:
[dependencies]
nc = "0.7"Examples
Get file stat:
let mut statbuf = nc::stat_t::default();
let path = "/etc/passwd";
#[cfg(not(target_arch = "aarch64"))]
let ret = unsafe { nc::stat(path, &mut statbuf) };
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
let ret = unsafe { nc::fstatat(nc::AT_FDCWD, path, &mut statbuf, 0) };
match ret {
Ok(_) => println!("s: {:?}", statbuf),
Err(errno) => eprintln!("Failed to get file status, got errno: {}", errno),
}Fork process:
let pid = unsafe { nc::fork() };
match pid {
Ok(pid) => {
if pid == 0 {
println!("child process: {}", pid);
let args = [""];
let env = [""];
match unsafe { nc::execve("/bin/ls", &args, &env) } {
Ok(_) => {},
Err(errno) => eprintln!("`ls` got err: {}", errno),
}
} else if pid < 0 {
eprintln!("fork() error!");
} else {
println!("parent process!");
}
},
Err(errno) => eprintln!("errno: {}", errno),
}Kill init process:
let ret = unsafe { nc::kill(1, nc::SIGTERM) };
assert_eq!(ret, Err(nc::EPERM));Or get system info:
pub fn cstr_to_str(input: &[u8]) -> &str {
let nul_index = input.iter().position(|&b| b == 0).unwrap_or(input.len());
std::str::from_utf8(&input[0..nul_index]).unwrap()
}
fn main() {
let mut uts = nc::utsname_t::default();
let ret = unsafe { nc::uname(&mut uts) };
assert!(ret.is_ok());
let mut result = Vec::new();
result.push(cstr_to_str(&uts.sysname));
result.push(cstr_to_str(&uts.nodename));
result.push(cstr_to_str(&uts.release));
result.push(cstr_to_str(&uts.version));
result.push(cstr_to_str(&uts.machine));
let domain_name = cstr_to_str(&uts.domainname);
if domain_name != "(none)" {
result.push(domain_name);
}
let result = result.join(" ");
println!("{}", result);
}Stable version
For stable version of rustc, please install a C compiler (gcc or clang) first.
As asm! feature is unavailable in stable version.
Platforms and Architectures
- linux
- x86
- x86-64
- arm
- aarch64
- mips
- mipsel
- mips64
- mips64el
- powerpc64
- s390x
- freebsd
- x86-64
Related projects
Re-exports
pub use types::*;Modules
Constants
Argument list too long
Permission denied
Address already in use
Cannot assign requested address
Advertise error
Address family not supported by protocol
Try again
Operation already in progress
Invalid exchange
Bad file number
File descriptor in bad state
Not a data message
Invalid request descriptor
Invalid request code
Invalid slot
Bad font file format
Device or resource busy
Operation Canceled
No child processes
Channel number out of range
Communication error on send
Software caused connection abort
Connection refused
Connection reset by peer
Resource deadlock would occur
Destination address required
Math argument out of domain of func
RFS specific error
Quota exceeded
File exists
Bad address
File too large
Host is down
No route to host
Memory page has hardware error
Identifier removed
Illegal byte sequence
Operation now in progress
Interrupted system call
Invalid argument
I/O error
Transport endpoint is already connected
Is a directory
Is a named type file
Key has expired
Key was rejected by service
Key has been revoked
Level 2 halted
Level 2 not synchronized
Level 3 halted
Level 3 reset
Can not access a needed shared library
Accessing a corrupted shared library
Cannot exec a shared library directly
Attempting to link in too many shared libraries
.lib section in a.out corrupted
Link number out of range
Too many symbolic links encountered
Wrong medium type
Too many open files
Too many links
Message too long
Multihop attempted
File name too long
No XENIX semaphores available
Network is down
Network dropped connection because of reset
Network is unreachable
File table overflow
No anode
No buffer space available
No CSI structure available
No data available
No such device
No such file or directory
Exec format error
Required key not available
No record locks available
Link has been severed
No medium found
Out of memory
No message of desired type
Machine is not on the network
Package not installed
Protocol not available
No space left on device
Out of streams resources
Device not a stream
Invalid system call number
Block device required
Transport endpoint is not connected
Not a directory
Directory not empty
Not a XENIX named type file
State not recoverable
Socket operation on non-socket
Not a typewriter
Name not unique on network
No such device or address
Operation not supported on transport endpoint
Value too large for defined data type
Owner died
Operation not permitted
Protocol family not supported
Broken pipe
Protocol error
Protocol not supported
Protocol wrong type for socket
Math result not representable
Remote address changed
Object is remote
Remote I/O error
Interrupted system call should be restarted
Operation not possible due to RF-kill
Read-only file system
Cannot send after transport endpoint shutdown
Socket type not supported
Illegal seek
No such process
Srmount error
Stale file handle
Streams pipe error
Timer expired
Connection timed out
Too many references: cannot splice
Text file busy
Structure needs cleaning
Protocol driver not attached
Too many users
Cross-device link
Exchange full
Functions
Set architecture-specific thread state.
Tune kernel clock. Returns clock state on success.
Get resolution(precision) of the specific clock.
Get time of specific clock.
High resolution sleep with a specific clock.
Set time of specific clock.
Copy a range of data from one file to another.
Unlock a kernel module.
Open an epoll file descriptor.
Open an epoll file descriptor.
Deprecated.
Wait for an I/O event on an epoll file descriptor.
Wait for an I/O event on an epoll file descriptor.
Deperecated.
Exit all threads in a process’s thread group.
Create and initialize fanotify group.
Add, remove, or modify an fanotify mark on a filesystem object
Load a kernel module.
List extended attribute names.
Remove an extended attribute.
Retrieve exported kernel and module symbols. Deprecated.
Retrieve NUMA memory policy for a thread
Get list of robust futexes.
Get thread-local storage information.
Get directory entries.
Get name of connected peer socket.
Get program scheduling priority.
Get current address to which the socket sockfd is bound.
Get options on sockets
Get time.
Load a kernel module.
Add a watch to an initialized inotify instance.
Initialize an inotify instance.
Initialize an inotify instance.
Remove an existing watch from an inotify instance.
Destroy the aio_context specified. May cancel any outstanding AIOs and block on completion.
Attempts to read at least min_nr events and up to nr events from the completion queue for the aio_context specified by ctx_id.
read asynchronous I/O events from the completion queue
Get I/O scheduling class and priority.
Set I/O scheduling class and priority.
Load a new kernel for later execution.
Load a new kernel for later execution.
List extended attribute names.
Return a directory entry’s path.
Remove an extended attribute.
sys_membarrier - issue memory barriers on a set of threads
Create an anonymous file.
Move all pages in a process to another set of nodes
mincore() returns the memory residency status of the pages in the current process’s address space specified by [addr, addr + len). The status is returned in a vector of bytes. The least significant bit of each byte is 1 if the referenced page is in memory, otherwise it is zero.
Move a mount from one place to another.
Move individual pages of a process to another node
Get/set message queue attributes
Receive a message from a message queue
Send message to a message queue.
Unlock memory.
Obtain handle for a filename
Get file status.
Syscall interface to kernel nfs daemon. Deprecated.
Obtain handle for an open file
Set up performance monitoring.
Set the process execution domain.
Obtain a duplicate of another process’s file descriptor.
Obtain a file descriptor that refers to a process.
sys_pidfd_send_signal - Signal a process through a pidfd
Change the root filesystem.
Create a new protection key.
Set protection on a region of memory.
Transfer data between process address spaces
Transfer data between process address spaces
Read value of a symbolic link.
Create a nonlinear file mapping. Deprecated.
Remove an extended attribute.
Request a key from kernel’s key management facility.
Restart a system call after interruption by a stop signal.
Examine and change a signal action.
Examine pending signals.
Change the list of currently blocked signals.
Queue a signal and data.
Return from signal handler and cleanup stack frame.
Wait for a signal.
Synchronously wait for queued signals.
Queue a signal and data.
Get static priority max value.
Get static priority min value.
Get a thread’s CPU affinity mask.
Get scheduling policy and attributes
Get scheduling paramters.
Get scheduling parameter.
Get the SCHED_RR interval for the named process.
Set a thread’s CPU affinity mask.
Set the RT priority of a thread.
Set scheduling paramters.
Set scheduling parameter.
Yield the processor.
System V semaphore operations
Set default NUMA memory policy for a thread and its children
Set the robust-futex list head of a task.
Set thread-local storage information.
Set pointer to thread ID.
Set NIS domain name.
Set hostname.
Set program scheduling priority.
Set options on sockets.
Set system time and timezone.
Get/set signal stack context.
Create a pair of connected socket.
Get errno description.
Sync a file segment to disk
Create a per-process timer
Delete a per-process timer
Get overrun count for a per-process timer.
Fetch state of per-process timer>
Arm/disarm state of per-process timer.
Create a timer that notifies via a file descriptor.
Get current timer via a file descriptor.
Set current timer via a file descriptor.
Create a file descriptor to handle page faults in user space.
Type Definitions
Error No.