Expand description
Execute system call directly without std
or libc
.
§Usage
Add this to Cargo.toml
:
[dependencies]
nc = "0.8"
§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.
§Supported Operating Systems and Architectures
- linux
- aarch64
- arm
- loongarch64
- mips
- mips64
- mips64el
- mipsel
- powerpc64
- riscv64
- s390x
- x86
- x86-64
- android
- aarch64
- freebsd
- x86-64
- netbsd
- x86-64
- mac os
- x86-64
§Related projects
Re-exports§
Modules§
Constants§
- Argument list too long
- Permission denied
- Address already in use
- Can’t assign requested address
- Address family not supported by protocol family
- Resource temporarily unavailable
- Operation already in progress
- Authentication error
- Bad CPU type in executable
- Bad executable
- Bad file descriptor
- Malformed Macho file
- Bad message
- RPC struct is bad
- Device / Resource busy
- Operation canceled
- No child processes
- Software caused connection abort
- Connection refused
- Connection reset by peer
- Resource deadlock avoided
- Destination address required
- Device error, e.g. paper out
- Numerical argument out of domain
- Disc quota exceeded
- File exists
- Bad address
- File too large
- Inappropriate file type or format
- Host is down
- No route to host
- Identifier removed
- Illegal byte sequence
- Operation now in progress
- Interrupted system call
- Invalid argument
- Input/output error
- Socket is already connected
- Is a directory
- Too many levels of symbolic links
- Too many open files
- Too many links
- Message too long
- Reserved
- File name too long
- Need authenticator
- Network is down
- Network dropped connection on reset
- Network is unreachable
- Too many open files in system
- Attribute not found
- No buffer space available
- No message available on STREAM
- Operation not supported by device
- No such file or directory
- Exec format error
- No locks available
- Reserved
- Cannot allocate memory
- No message of desired type
- No such policy registered
- Protocol not available
- No space left on device
- No STREAM resources
- Not a STREAM
- Function not implemented
- Block device required
- Socket is not connected
- Not a directory
- Directory not empty
- State not recoverable
- Socket operation on non-socket
- Operation not supported
- Inappropriate ioctl for device
- Device not configured
- Operation not supported on socket
- Value too large to be stored in data type
- Previous owner died
- Operation not permitted
- Protocol family not supported
- Broken pipe
- Too many processes
- Bad procedure for program
- Program version wrong
- RPC prog. not avail
- Protocol error
- Protocol not supported
- Protocol wrong type for socket
- Device power is off
- Interface output queue is full
- Result too large
- Too many levels of remote in path
- Read-only file system
- RPC version wrong
- Shared library version mismatch
- Can’t send after socket shutdown
- Socket type not supported
- Illegal seek
- No such process
- Stale NFS file handle
- STREAM ioctl timeout
- Operation timed out
- Too many references: can’t splice
- Text file busy
- Too many users
- Cross-device link
Functions§
- Accept a connection on a socket.
- Accept a connection on a socket.
- Check user’s permission for a file.
- acct⚠Switch process accounting.
- Correct the time to allow synchronization of the system clock.
- Cancel an outstanding asynchronous I/O operation (REALTIME)
- Retrieve error status of asynchronous I/O operation
- Asynchronous file synchronization (REALTIME)
- Asynchronous read from a file (REALTIME)
- Retrieve return status of asynchronous I/O operation (REALTIME)
- Suspend until asynchronous I/O operations or timeout complete (REALTIME)
- Asynchronous write to a file (REALTIME)
- Commit BSM audit record to audit log
- Configure system audit parameters
- Configure system audit parameters
- bind⚠Bind a name to a socket.
- Change working directory.
- Set file flags.
- Change permissions of a file.
- Change permissions of a file.
- Change ownership of a file.
- Change the root directory.
- Close a file descriptor.
- Close a file descriptor.
- Initialize a connection on a socket.
- Initialize a connection on a socket.
- Copy a file.
- dup⚠Create a copy of the file descriptor
oldfd
, using the lowest available file descriptor. - dup2⚠Create a copy of the file descriptor
oldfd
, using the speficified file descriptornewfd
. - Execute a new program.
- exit⚠Terminate current process.
- Check user’s permission for a file.
- Change working directory.
- Set file flags.
- Change permissions of a file.
- Change permissions of a file.
- Change ownership of a file.
- Change ownership of a file.
- manipulate file descriptor.
- Flush all modified in-core data (exclude metadata) refered by
fd
to disk. - Get extended attribute value.
- Opens the file referenced by
fh
for reading and/or writing, and returns the file descriptor to the calling process. - List extended attribute names.
- Apply or remove an advisory lock on an open file.
- Mount filesystem.
- fork⚠Create a child process.
- Get configurable pathname variables
- Remove an extended attribute.
- Set extended attribute value.
- Get file status about a file descriptor.
- Get file status.
- Get file status.
- Get file status.
- Get filesystem statistics.
- Get filesystem statistics.
- Flush all modified in-core data refered by
fd
to disk. - Flush all modified in-core data refered by
fd
to disk. - Truncate an opened file to a specified length.
- Change timestamp of a file.
- Retrieve audit session state
- Retrieve audit session ID
- Get directory entries in a file system independent format
- Get file descriptor limit
- Get the effective group ID of the calling process.
- Get the effective user ID of the calling process.
- Get file handle.
- Get list of all mounted file systems.
- Get the real group ID of the calling process.
- Get list of supplementary group Ids.
- Get value of an interval timer.
- Get login name.
- Get name of connected peer socket.
- Returns the PGID(process group ID) of the process specified by
pid
. - Get the process group ID of the calling process.
- Get the process ID (PID) of the calling process.
- Get the process ID of the parent of the calling process.
- Get program scheduling priority.
- Get resource limit.
- Get resource usage.
- Get session Id.
- Get current address to which the socket
sockfd
is bound. - Get options on sockets
- Get the caller’s thread ID (TID).
- Get time.
- Get the real user ID of the calling process.
- Get extended attribute value.
- Control device.
- Is current process tainted by uid or gid changes
- kill⚠Send signal to a process.
- Creates a new kernel event queue and returns a descriptor.
- Change ownership of a file. Does not deference symbolic link.
- link⚠Make a new name for a file.
- Make a new name for a file.
- List directed I/O (REALTIME)
- Listen for connections on a socket.
- List extended attribute names.
- Reposition file offset.
- Get file status about a file, without following symbolic.
- Get file status about a file, without following symbolic.
- Give advice about use of memory.
- 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.
- Control the inheritance of pages
- Create a directory.
- Create a directory.
- Create a fifo file.
- Create a special or ordinary file.
- Lock memory.
- Lock memory.
- mmap⚠Map files or devices into memory.
- Mount filesystem.
- Set protection on a region of memory.
- System V message control operations.
- Get a System V message queue identifier.
- Receive messages from a System V message queue.
- Append the message to a System V message queue.
- Synchronize a file with memory map.
- Unlock memory.
- Unlock memory.
- Unmap files or devices from memory.
- Used by the NFS daemons to pass information into and out of the kernel and also to enter the kernel as a server daemon.
- Used by the NTP daemon to adjust the system clock to an externally derived time.
- Provides the time, maximum error (sync distance) and estimated error (dispersion) to client user application programs.
- open⚠Open and possibly create a file.
- Open and possibly create a file within a directory.
- Open and possibly create a file within a directory.
- Get configurable pathname variables
- Freeze the specified process (provided in args->pid), or find and freeze a PID.
- pipe⚠Create a pipe.
- Change the root filesystem.
- poll⚠Wait for some event on file descriptors.
- Read from a file descriptor without changing file offset.
- Read from a file descriptor without changing file offset.
- Process trace.
- Write to a file descriptor without changing file offset.
- Write to a file descriptor without changing file offset.
- Manipulate disk quotes.
- read⚠Read from a file descriptor.
- Read value of a symbolic link.
- Read value of a symbolic link.
- Read from a file descriptor into multiple buffers.
- Reboot or enable/disable Ctrl-Alt-Del.
- Receive a message from a socket.
- Receive a msg from a socket.
- Remove an extended attribute.
- Change name or location of a file.
- Change name or location of a file.
- Revoke file access
- Delete a directory.
- Sychronous I/O multiplexing.
- Sychronous I/O multiplexing.
- Close an semaphore.
- Creates or opens the named semaphore specified by
name
. - Increment (unlock) a semaphore.
- Decrement (lock) a semaphore.
- Remove an semaphore.
- Decrement (lock) a semaphore.
- Decrement (lock) a semaphore.
- System V semaphore control operations
- Get a System V semphore set identifier.
- System V semphore operations.
- Transfer data between two file descriptors.
- Send a message on a socket. Allow sending ancillary data.
- Send a message on a socket. Allow sending ancillary data.
- Send a message on a socket.
- Send a message on a socket.
- Set audit session state
- Set audit session ID
- Set the effective group ID of the calling process to
gid
. - Set the effective user ID of the calling process to
uid
. - Set the group ID of the calling process to
gid
. - Set list of supplementary group Ids.
- Set value of an interval timer.
- Set login name.
- Set the process group ID (PGID) of the process specified by
pid
topgid
. - Set program scheduling priority.
- Set real and effective group IDs of the calling process.
- Set real and effective user IDs of the calling process.
- Set resource limit.
- Create a new session if the calling process is not a process group leader.
- Set options on sockets.
- Set the per-thread override identity.
- Set the per-thread override identity.
- Set system time and timezone.
- Set user ID of the calling process to
uid
. - Set extended attribute value.
- Opens (or optionally creates) a POSIX shared memory object named
path
. - Removes a shared memory object named
path
. - Attach the System V shared memory segment.
- System V shared memory control.
- Detach the System V shared memory segment.
- Allocates a System V shared memory segment.
- Shutdown part of a full-duplex connection.
- Examine and change a signal action.
- Get/set signal stack context.
- Examine pending signals.
- Examine and change blocked signals.
- Return from signal handler and cleanup stack frame. Never returns.
- Wait for a signal.
- Create an endpoint for communication.
- Create a pair of connected socket.
- stat⚠Get file status about a file.
- Get file status about a file.
- Get filesystem statistics.
- Get filesystem statistics.
- Get errno description.
- Start swapping to file/device.
- Make a new name for a file.
- Make a new name for a file.
- sync⚠Commit filesystem caches to disk.
- Truncate a file to a specified length.
- Set file mode creation mask.
- Attempt to recover a deleted file
- Delete a name and possibly the file it refers to.
- Delete a name and possibly the file it refers to.
- Unmount filesystem.
- Change file last access and modification time.
- Create a child process and wait until it is terminated.
- Wait for process to change state.
- Wait for process to change state.
- Write to a file descriptor.
- Write to a file descriptor from multiple buffers.