0% found this document useful (0 votes)
12 views80 pages

LP Unit 3

This document provides an overview of system calls in Linux and UNIX-like systems, focusing on file management and process control. It details various system calls such as open(), read(), write(), and their usage in managing files and processes. Additionally, it explains the types of system calls, including process control, file management, device management, information maintenance, and communication.

Uploaded by

hannanthesec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views80 pages

LP Unit 3

This document provides an overview of system calls in Linux and UNIX-like systems, focusing on file management and process control. It details various system calls such as open(), read(), write(), and their usage in managing files and processes. Additionally, it explains the types of system calls, including process control, file management, device management, information maintenance, and communication.

Uploaded by

hannanthesec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 80

UNIT - 3

System Calls
UNIT - 3
• Introduction to system calls and file management, Regular file
management system calls – open( ), read(), write(), lseek(),
Close(),unlink( ),stat( ), getdents( ). file management system
calls – chown() and fchown(), chmod() and fchmod( ), dup( )
and dup2( ), fcntl(), ioctl(), link(), mknod(), sync(), truncate( )
and ftruncate( ).

Creating a new process – fork( ),orphan processes,


terminating a process – exit( ) zombie processes, waiting
for a child – wait( ), Differentiating a process – exec( ),
changing directories – chdir( ), changing priorities- nice( ),
Accessing user and Group ID’s.
System Call()
• In Linux (and UNIX-like systems), system
calls provide the interface between user
programs and the operating system.
• They are used for various tasks such as
process control, file management,
communication, etc.
• In the context of file management, system
calls allow programs to interact with files—
creating, reading, writing, and managing them.
System Call()
When the process is being run, if
the process requires certain actions
that need to be carried out by
Operating System, the process has
to go call the function which can
interact with the kernel to complete
the actions. This special type of
function call is known as System
Calls in OS.
System Call()
• In our computer system, we have two modes available.
• User Mode: In this mode, execution is done on behalf of the
user.
• Monitor/Kernel-Mode: In this mode, execution is done on
behalf of OS.
System Call()
• Types of System Calls in OS
• There are mainly 5 types of system calls available:
• Process Control
• File Management
• Device Management
• Information Maintenance
• Communication
System Call()
Process Control: It handles the system calls for process creation, deletion, etc.
Examples of process control system calls are: Load, Execute, Abort, and Wait for Signal
events for process.
File Management: File manipulation events like Creating, Deleting, Reading
Writing etc are being classified under file management system calls.
Device Management: Device Management system calls are being used to request the
device, release the device, and logically attach and detach the device.
Information Maintenance: This type of system call is used to maintain the information
about the system like time and date.
Communications: In order to have interprocess communications like send or receive
the message, create or delete the communication connections, to transfer status
information etc. communication system calls are used.
File Management
• File management system calls in Linux (and UNIX-like
systems) provide an interface for interacting with the file
system.
• These system calls allow operations such as opening, reading,
writing, closing, seeking, and manipulating file permissions
and metadata.
• Below are the most commonly used system calls for file
management:
Open() system call
The open() system call is used in Linux (and UNIX-like systems) to open a file and
return a file descriptor that can be used to perform other file-related operations such as
reading, writing, or closing the file.

int open(const char *pathname, int flags);


int open(const char *pathname, int flags, mode_t mode); // For creating a file

pathname: The path to the file that you want to open. Return Value:
•On success: It returns a file
flags: Specifies the mode in which the file should be opened.
descriptor (a non-negative
O_RDONLY: Open for reading only. integer).
•On failure: It returns -1 and sets
O_WRONLY: Open for writing only.
errno to indicate the error.
O_RDWR: Open for both reading and writing.
O_CREAT: Create the file if it does not exist (requires a third argument mode).
O_TRUNC: Truncate the file to zero length if it already exists.
O_APPEND: Append to the file if it already exists .
mode (optional): permissions for the newly created file (e.g., 0644 for read/write permissions).
Program for open() system call:
#include <stdio.h>
#include <fcntl.h> // For open()
#include <unistd.h> // For close()
int main() {
// Step 1: Open or create the file using open() system call
int fd = open("example.txt", O_RDWR | O_CREAT, 0644);

// Step 2: Check if the file was opened successfully


if (fd == -1) {
perror("Error opening/creating file");
return 1; // Return error code
}
printf("File opened/created successfully with file descriptor: %d\n", fd);
// Step 3: Close the file
if (close(fd) == -1) {
perror("Error closing the file");
return 1;
}
return 0; // Program successful
}
read() system call
Purpose: Reads data from a file.
Prototype:
ssize_t read(int fd, void *buf, size_t count);
•Parameters:
•fd: File descriptor from open().
•buf: Buffer to store the data.
•count: Number of bytes to read.
•Return: Number of bytes read or -1 on error.
Program for read() system call:
write() system call
Purpose: Writes data to a file.
•Prototype:
ssize_t write(int fd, const void *buf, size_t count);
•Parameters:
•fd: File descriptor from open().
•buf: Buffer containing data to write.
•count: Number of bytes to write.
•Return: Number of bytes written or -1 on error.
Program for write() system call:
lseek() system call
Purpose: Repositions the file offset (cursor).
Prototype: off_t lseek(int fd, off_t offset, int whence);
Parameters:
fd: File descriptor.
offset: Number of bytes to move.
whence: Position relative to:
SEEK_SET: Set to offset bytes from the beginning.
SEEK_CUR: Move offset bytes from the current position.
SEEK_END: Move offset bytes from the end of the file.
Return: New file offset or -1 on error.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
// Step 1: Open or create the file in read/write mode
int fd = open("example.txt", O_RDWR | O_CREAT, 0644);
// Check if the file was opened successfully
if (fd == -1) {
perror("Error opening/creating file");
return 1; // Return error code
}
// Step 2: Write to the file
const char *text = "Hello, lseek example!\n";
ssize_t bytes_written = write(fd, text, strlen(text));

if (bytes_written == -1) {
perror("Error writing to file");
close(fd);
return 1;
}
printf("Successfully wrote %ld bytes to the file.\n", bytes_written);
unlink() system call
• The unlink() system call is used to delete a file from the file system.
• It removes the directory entry, and if no other process is using the file, the
system will free up the file’s resources.
#include <stdio.h>
#include <unistd.h> // For unlink()

int main()
{
// Step 1: Delete the file "example.txt"
if (unlink("example.txt") == -1)
{
perror("Error deleting file");
return 1; // Return error code
}

printf("File deleted successfully.\n");


return 0; // Program successful
}
stat() system call
stat() system call retrieves information about a file, such as its size,
permissions, and timestamps. It fills a structure with file details.
getdents() system call
• The getdents() system call reads directory entries from a file
descriptor that points to a directory.
• It fills a buffer with directory entries, and it’s a low-level system
call that requires a more complex structure to interpret.
• Example Directory Structure:
Assume your current directory Expected Output:
• file1.txt Found file: .
• file2.txt Found file: ..
Found file: file1.txt
• Subdir1
Found file: file2.txt
• subdir2 Found file: subdir1
Found file: subdir2

. Represents the current directory


.. Represents the parent directory.
chown()
• The chown() system call is used to change the owner
and group of a file.
Syntax:
int chown(const char *pathname, uid_t owner, gid_t group);

• pathname: The path to the file.


• owner: The new user ID (UID) for the file owner.
• group: The new group ID (GID) for the file group.
• Returns: 0 on success, -1 on error.
chown()
#include <stdio.h>
#include <unistd.h> // For chown()

int main()
{
// Change owner and group of "example.txt" to UID 1000 and GID 1000
if (chown("example.txt", 1000, 1000) == -1)
{
perror("Error changing ownership");
return 1;
}

printf("Ownership changed successfully.\n");


return 0;
}
fchown()
• The fchown() system call performs the same action as
chown(), but it operates on an open file descriptor
instead of a file path.
• Syntax:
• int fchown(int fd, uid_t owner, gid_t group);
• fd: The file descriptor of the file.
• owner: The new user ID (UID) for the file owner.
• group: The new group ID (GID) for the file group.
• Returns: 0 on success, -1 on error.
fchown()
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return 1;
}
// Change owner and group of the file (represented by the file descriptor)
if (fchown(fd, 1000, 1000) == -1) {
perror("Error changing ownership");
close(fd);
return 1;
}
printf("Ownership changed successfully.\n");
close(fd); return 0;
}
dup(),
• The dup() system call duplicates a file descriptor, making a copy
of it.
• The copy will have the lowest available file descriptor number.

int dup(int oldfd);


• oldfd: The file descriptor you want to duplicate.
• Returns: The new file descriptor on success, -1 on error.
dup()
#include <stdio.h>
#include <unistd.h>
int main() {
// Duplicate stdout (file descriptor 1)
int newfd = dup(1);
if (newfd == -1) {
perror("Error duplicating file descriptor");
return 1;
}
// Write to the new file descriptor (should behave like stdout)
write(newfd, "This is written to the duplicated stdout.\n", 42);
return 0;
}
The program duplicates the file descriptor 1 (which is stdout) and returns a new file
descriptor newfd. Writing to newfd behaves the same as writing to the original stdout.
dup2()
• The dup2() system call duplicates a file descriptor but allows
you to specify the new file descriptor number.
• If the new file descriptor already exists, it is closed before
being reused.

int dup2(int oldfd, int newfd);

• oldfd: The file descriptor to duplicate.


• newfd: The file descriptor number where you want to
duplicate the file descriptor to.
• Returns: newfd on success, -1 on error.
dup2()
#include <stdio.h>
#include <unistd.h>
int main()
{
// Redirect stdout (file descriptor 1) to stderr (file descriptor 2)
if (dup2(2, 1) == -1) {
perror("Error duplicating file descriptor");
return 1;
}
// Now, writing to stdout will actually write to stderr
printf("This message is redirected to stderr!\n");
return 0;
}
dup2()
• File Descriptor Basics:
• File descriptors in Unix represent open files or input/output streams.
• 0: Standard Input (stdin) 1: Standard Output (stdout) 2: Standard Error (stderr)
• By default, printf() writes to stdout (file descriptor 1), and error messages are printed to stderr
(file descriptor 2).
• dup2(2, 1):This call duplicates the file descriptor 2 (stderr) to file descriptor 1 (stdout).After this,
anything written to stdout (e.g., via printf) is redirected to stderr.
• Closing the Existing newfd (1):If newfd (stdout in this case) is open, dup2() first closes it and
then duplicates oldfd (stderr) to it.
• If newfd is already closed, dup2() just duplicates without closing anything.Behavior After
Duplication:After dup2(2, 1), writing to file descriptor 1 (stdout) actually writes to file descriptor
2 (stderr).
• The printf() call, which usually writes to stdout, now sends its output to stderr.
fcntl()
• fcntl() System Call in Detail The fcntl() system call provides a
way to perform various operations on file descriptors in Unix-
like systems.
• It's a versatile function that can manipulate file descriptor
properties, control file locks, and handle non-blocking I/O.

int fcntl(int fd, int cmd, ... /* arg */);

• fd: The file descriptor to operate on.


• cmd: The command that specifies the operation to be
performed.
• arg: Optional argument, depending on the command (some
commands do not require it).
fcntl()
• Common fcntl() Commands (cmd):
• F_DUPFD: Duplicates the file descriptor to the lowest
available value greater than or equal to arg.
• F_GETFD: Gets the file descriptor flags.
• F_SETFD: Sets the file descriptor flags (like the close-on-exec
flag FD_CLOEXEC).F_GETFL: Gets the file status flags
(e.g., O_RDONLY, O_NONBLOCK).
• F_SETFL: Sets the file status flags (e.g., O_APPEND,
O_NONBLOCK).
• F_GETLK, F_SETLK, F_SETLKW: Used for managing file
locks.
fcntl()
ioctl()
• ioctl() System Call in Detail The ioctl() (input/output control) system call in
Unix-like operating systems is used to manipulate the underlying device
parameters of special files.
• It provides a way for user-space applications to send control commands to
device drivers or perform various operations on file descriptors that are not
covered by standard system calls like read() and write().

int ioctl(int fd, unsigned long request, ...);


fd: The file descriptor for the device or special file on which the command is to be
performed.
request: A request code that specifies the operation to be performed
....: An optional argument that depends on the request being performed. This can be a
pointer to a data structure or a value needed for the operation.
ioctl()
Common ioctl() Commands:
The specific commands that can be used with ioctl() are defined in
various headers
(such as <linux/ioctl.h>, <sys/ioctl.h>, and others) and vary by
device type. Here are some examples:
•Terminal Control:
•TCGETS: Get the current terminal attributes.
•TCSETS: Set the terminal attributes.
•Network Interfaces:
•SIOCGIFADDR: Get the IP address associated with a network
interface.
•SIOCSIFADDR: Set the IP address for a network interface.
•File System Operations:
•FIONREAD: Get the number of bytes available for reading.
ioctl()
link() System Call in Detail
• The link() system call in Unix-like operating systems is used to create a
hard link to an existing file.
• A hard link is an additional directory entry for an existing file, allowing
you to access the same file content through different filenames.

Syntax: int link(const char *oldpath, const char *newpath);


oldpath: The path to the existing file (the target of the link).
newpath: The path where the new hard link will be created.
link() to create a hard link
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
const char *source_file = "example.txt"; // Original file
const char *link_name = "example_link.txt"; // Hard link name
// Create a hard link link() to create a hard link
if (link(source_file, link_name) == -1) {
perror("Error creating hard link");
return 1;
}
printf("Hard link created: %s -> %s\n", link_name, source_file);
return 0;
}
mknod() System Call
mknod() System Call
•The mknod() system call is used to create a special file (such as a
device file) in a filesystem.
• It can be used to create block and character device files.

pathname: The name of the file to be created.


mode: The file type and permissions (should be set using macros
like S_IFREG, S_IFCHR, or S_IFBLK).
dev: The device ID (usually obtained using makedev() for block
and character devices).
Return Value: Returns 0 on success.
Returns -1 on failure and sets errno.
mknod() System Call
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
const char *device_name = "/dev/mydevice"; // Device file path
mode_t mode = S_IFCHR | 0666; // Character device with read/write permissions
dev_t dev_id = makedev(10, 200); // Major and minor device numbers
if (mknod(device_name, mode, dev_id) == -1) {
perror("Error creating device file");
return 1;
}
printf("Device file created: %s\n", device_name);
return 0;
}
sync() System Call
• sync() System Call The sync() system call is used to flush the
file system buffers, ensuring that all modified data is written to
the disk.
sync() System Call
truncate() System Call
• The truncate() system call is used to change the size of a file.
If the new size is smaller than the current size, the file is
truncated to the new size.
• If it is larger, the file is extended, and the added space is filled
with zeros.
int truncate(const char *path, off_t length);

path: The path of the file to be truncated.


length: The new size for the file.
Return Value:Returns 0 on success.
Returns -1 on failure and sets errno.
truncate() System Call
#include <stdio.h>
#include <unistd.h>
int main() {
const char *filename = "example.txt";
off_t new_size = 10; // New size in bytes
if (truncate(filename, new_size) == -1) {
perror("Error truncating file");
return 1;
}
printf("File truncated to %ld bytes.\n", new_size);
return 0;
}
ftruncate() System Call
• fd: The file descriptor of the file to be truncated.length: The new
size for the file.Return Value:Returns 0 on success.Returns -1 on
failure and sets errno.
int ftruncate(int fd, off_t length);

fd: The file descriptor of the file to be truncated.

length: The new size for the file.

Return Value:Returns 0 on success.

Returns -1 on failure and sets errno.


ftruncate() System Call
Creating a New Process
• The fork() system call in Unix-like operating
systems is used to create a new process by
duplicating the current (parent) process.
• The new process is called the "child" process,
and it runs as a separate entity in the system.
• Both the parent and the child continue executing
the same program, but they do so independently,
with different memory spaces.
Creating a New Process
• Syntax: pid_t fork(void);
• Return value:0 to the child process.
• A positive process ID (PID) of the child to the
parent process.
• -1 in case of failure (e.g., resource exhaustion).
Creating a New Process
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork(); // Create a new process
if (pid == -1) {
perror("Error in fork");
return 1;
}
if (pid == 0) {
// Child process
printf("Hello from the child process! PID: %d\n", getpid());
} else {
// Parent process
printf("Hello from the parent process! PID: %d\n", getpid());
} Output:
return 0; } Hello from the parent process! PID: 1234
Hello from the child process! PID: 1235
Creating a New Process
• pid_t pid = fork();This line creates a new process using the fork()
system call.
• If successful, fork() will return 0 to the child process and the child's
PID (Process ID) to the parent process.
• If it fails, it returns -1.
• Error Handling:If fork() returns -1, it means the creation of the new
process failed.
• In this case, the program will print "Error in fork" using perror()
and return with exit status 1.
• Child Process:If pid == 0, it means we are inside the child process.
The child process prints its own PID using the getpid() system call.
• Parent Process:If pid > 0, we are inside the parent process, and the
parent prints its own PID.
Process Hierarchy
The main process: P0
Processes created by the 1st fork: P1
Processes created by the 2nd fork: P2, P3
Processes created by the 3rd fork: P4, P5, P6, P7
Orphan Processes
• An orphan process is a child process that continues to
run even after its parent process has terminated.
• In Unix-like operating systems, if a parent process
ends before its child process, the child process
becomes an orphan.
• These orphan processes are adopted by the init
process (PID 1), which becomes their new parent.
• The init process is responsible for "reaping" orphan
processes, ensuring they are properly handled and do
not become zombie processes (terminated but not
cleaned up).
#include <stdio.h>
Orphan Processes
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork(); // Create a new process
if (pid == -1) {
perror("Error in fork"); Parent process terminating. PID: 1234 I am an
return 1; orphan process. My PID: 1235, My parent PID: 1
}
if (pid == 0) {// Child process
sleep(5); // Sleep to let the parent process terminate first
printf("I am an orphan process. My PID: %d, My parent PID: %d\n", getpid(),
getppid());
} else {// Parent process
printf("Parent process terminating. PID: %d\n", getpid());
exit(0); // Parent process exits, making the child an orphan
}
return 0;
}
Terminating a Process – exit()
• In Unix-like operating systems, the exit() system call is used to
terminate a process.
• When a process calls exit(), it performs the following tasks:
• Closes all open file descriptors.

• Releases any resources used by the process.

• Returns an exit status code to the operating system or parent


process.
• The process transitions into a zombie state until the parent
process reads its exit status.
Terminating a Process – exit()
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("The process is about to exit.\n");
exit(0); // Terminates the process with status code 0
}

In this example, the program prints a message and then terminates with an exit
code of 0. After the exit() call, the process is removed from the active
processes, but before it is fully cleaned up by the system, it may briefly become
a zombie process.
Zombie Process
• A zombie process is a process whose execution is
completed but it still has an entry in the process table.
• Zombie processes usually occur for child processes, as
the parent process still needs to read its child’s exit
status.
• Once this is done using the wait system call, the zombie
process is eliminated from the process table. This is
known as reaping the zombie process.
Zombie Process
Zombie Process

Child process is terminating. PID:


12345 Parent process is sleeping. PID:
12344
waiting for a child – wait( )
• A call to wait() blocks the calling process until one of its child processes exits or a signal
is received. After the child process terminates, parent continues its execution after wait
system call instruction.
• Child process may terminate due to any of these:
– It calls exit();
– It returns (an int) from main
– It receives a signal (from the OS or another process) whose default action is to
terminate.
waiting for a child – wait( )
• Syntax:#include <sys/wait.h>
#include <unistd.h>
// Waits for a child process to terminate and returns its PID
pid_t wait(int *stat_loc);

• Behavior of wait
– If the parent process has multiple children, the wait() call will cause the parent to
wait until any child process terminates.
– If a child process terminates, wait() returns the PID of the terminated child.
– If multiple child processes terminate, wait() will reap any one of them arbitrarily and
return its PID.
– If no children exist, wait() immediately returns -1.
waiting for a child – wait( )

Child process exiting. PID: 12345


Parent sleeping for 10 seconds.
Child will become a zombie.
Parent process waking up.
Child process reaped. No longer a zombie.
waiting for a child – wait( )
• Child status information:
Status information about the child reported by wait is more than just the
exit status of the child, it also includes
– normal/abnormal termination
– termination cause
– exit status
• To find information about status, we use
WIF….macros
– WIFEXITED(status): child exited normally
– WEXITSTATUS(status): return code when child exits
– WIFSIGNALED(status): child exited because a signal was not caught
– WTERMSIG(status): gives the number of the terminating signal
– WIFSTOPPED(status): child is stopped
– WSTOPSIG(status): gives the number of the stop signal
exec() Family of Functions
• The exec() family of system calls is used in Unix-like
operating systems to replace the current process image with a
new process image.
• Essentially, a process that calls exec() stops executing its
original program and starts executing a completely new
program.
• Unlike fork(), which creates a new process, exec() transforms
the current process into a new program, retaining the same
process ID (PID).
• The exec() family does not return to the calling program if
successful because the new process replaces the current one.
exec() Family of Functions
• exec() family consists of several functions, each with slightly
different features but the same core purpose: replacing the
current process image. Some common members include:
• execl(): Takes a variable list of arguments.
• execv(): Takes a vector (array) of arguments.
• execle(): Takes a variable list of arguments and allows
specifying the environment.
• execve(): Takes a vector of arguments and an array of
environment variables.
• execlp(): Same as execl(), but looks for the file in PATH.
• execvp(): Same as execv(), but looks for the file in PATH.
exec() Family of Functions
General Syntax:
•int execv(const char *path, char *const argv[]);

•path: The file path to the program that will replace the current
process.
•argv[]: An array of strings (arguments) passed to the new program,
where the last element must be NULL.
•If execv() or any other exec() function is successful, it does not
return. If there is an error, it returns -1.
exec() Family of Functions

Child process before exec()


Parent process ...
(output of `ls -l` command) ...
Difference between exec() and fork()
exec()
fork()

It is a system call in the C


1. It is a system call of operating system
programming language

It does not creates new process, but it


It is used to create a new
2. will replace the image of the current
process
process

exec() returns nothing to the calling


Its return value is an integer function if successful. It returns -1 if
3.
type unsuccessful

It does not takes any It takes parameters for filename/path,


4.
parameters. process, and environment

It creates a new process In exec() the machine code, data, heap,


5. that runs independently with and stack of the process are replaced by
Changing Directories: chdir()
• The chdir() system call is used to change the current
working directory of a process.
• In Unix-like operating systems, every process
operates in a current working directory from which it
references relative file paths.
• By using chdir(), a process can change its working
directory to another directory.
Changing Directories: chdir()
int chdir(const char *path);
path: A string representing the new directory
path. This can be an absolute path (e.g.,
/home/user) or a relative path (e.g., ../folder).
Returns:0 on success.-1 on failure, and errno is
set to indicate the error (e.g., if the directory does
not exist).
Changing Directories: chdir()

Successfully changed directory to /home


Current working directory: /home
Changing Process Priorities: nice()
System Call
• The nice() system call is used in Unix-like operating
systems to change the priority of a running process.
• It allows a user to specify a "niceness" value that affects
the process's scheduling priority.
• A higher niceness value means lower priority (the
process is "nicer" to others), while a lower (or negative)
niceness value means higher priority.
Changing Process Priorities: nice()
System Call
Syntax:
int nice(int increment);
increment: An integer value that indicates how much to increase the
niceness of the process.
The range of values typically allowed is from -20 (highest priority)
to 19 (lowest priority).
Only super user can give negative increment (increase priority)
Returns:The new niceness value on success.
-1 on failure, and errno is set to indicate the error.
Changing Process Priorities: nice() System Call

Current niceness: 0
New niceness: 5
Accessing User and Group IDs
• Every user in Unix like operating system is identified by a different integer
number, this unique number is called as UserID.
• These IDs determine the permissions and access rights of the process.
• The getuid(), getgid(), geteuid(), and getegid() system calls are used to access
these IDs.
• There are three types of UID defined for a process, which can be dynamically
changed as per the privilege of task.
• The three different types of UIDs defined are :
• 1. Real UserID
• 2. Effective UserID
• 3. Saved UserID
Accessing User and Group IDs
• 1. Real UserID : For a process, Real UserId is simply the UserID of the user
that has started it. It defines which files that this process has access to.
• 2. Effective UserID : It is normally the same as Real UserID, but sometimes it
is changed to enable a non-privileged user to access files that can only be
accessed by a privileged user like root.
• 3. Saved UserID : It is used when a process is running with elevated privileges
(generally root) needs to do some under-privileged work, this can be achieved
by temporarily switching to a non-privileged account.
• While performing under-privileged work, the effective UID is changed to some
lower privilege value, and the euid is saved to saved userID(suid), so that it can
be used for switching back to a privileged account when the task is completed.
Accessing User and Group IDs
Accessing User and Group IDs
• User and Group IDs:
• User ID (UID): A unique identifier for a user. Each user on
the system has a distinct UID.
• Group ID (GID): A unique identifier for a group. Users can
belong to one or more groups, and each group has a distinct
GID.
• Effective User ID (EUID): The UID used by the kernel to
determine the permissions for a process. It can be different
from the real UID when a program is executed with elevated
permissions (e.g., setuid programs).
• Effective Group ID (EGID): The GID used by the kernel to
determine group permissions for a process.
Accessing User and Group IDs
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
uid_t uid, euid;
gid_t gid, egid;
uid = getuid(); Output:
euid = geteuid();
Real UID: 1000
Effective UID: 1000
gid = getgid();
Real GID: 1000
egid = getegid();
Effective GID: 1000
printf("Real UID: %d\n", uid);
printf("Effective UID: %d\n", euid);
printf("Real GID: %d\n", gid);
printf("Effective GID: %d\n", egid);
return 0;
}
Setting User and Group IDs

You might also like