0% found this document useful (0 votes)
5 views14 pages

Linux File and Process Management Syscalls

The document provides an overview of various system calls in Linux for file and process management, including link(), symlink(), unlink(), and file information retrieval methods like stat(), fstat(), and lstat(). It also covers process creation and management through fork(), vfork(), wait(), and exec() system calls, as well as signal handling mechanisms. Additionally, it details inter-process communication (IPC) using semaphores, message queues, and shared memory.

Uploaded by

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

Linux File and Process Management Syscalls

The document provides an overview of various system calls in Linux for file and process management, including link(), symlink(), unlink(), and file information retrieval methods like stat(), fstat(), and lstat(). It also covers process creation and management through fork(), vfork(), wait(), and exec() system calls, as well as signal handling mechanisms. Additionally, it details inter-process communication (IPC) using semaphores, message queues, and shared memory.

Uploaded by

Anuj Yadav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

link() - Create a Hard Link


The link() system call creates a *hard link between two files. A hard link makes
two file names point to the same underlying inode, meaning they share the same
physical file data.

Syntax: -
int link(const char *oldpath, const char *newpath);
Parameters:
- oldpath: Path to the existing file.
- newpath: Path for the new hard link.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Hard links share the same inode.
- Deleting one link doesn’t affect the other.
- Hard links cannot span across filesystems.

2. symlink() - Create a Symbolic (Soft) Link


The symlink() system call creates a symbolic link, which is a special type of file that
points to another file or directory.
Syn: -
int symlink(const char *target, const char *linkpath);
Parameters:
- target: Path to the target file or directory.
- linkpath: Path for the new symbolic link.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Symbolic links point to the file path, not the inode.
- They can span across filesystems.
- If the target file is removed, the symlink becomes broken (dangling).

3. unlink() - Remove a File or Link


The unlink() system call removes a file or a symbolic link. For files with multiple
hard links, only the specified link is removed.
int unlink(const char *pathname);
Parameters:
- pathname: Path to the file or symbolic link to be removed.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Removes the link between the filename and its inode.
- If no links remain, the file is deleted when it’s no longer in use.
The stat, fstat, and lstat system calls in Linux are used to retrieve information
about files and their attributes. Here's an overview of each:
1. stat()- Get File Information
The stat() system call retrieves file information by following symbolic links to their
targets.
Syntax:
int stat(const char *pathname, struct stat *statbuf);
Parameters:
- pathname: Path to the file.
- statbuf: Pointer to a `struct stat` that will hold the file's information.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Follows symbolic links.
- Provides details such as file size, permissions, timestamps, and inode number.

2. fstat() - Get File Information from a File Descriptor


The fstat() system call retrieves file information for an open file using its file
descriptor.
Syntax:
int fstat(int fd, struct stat *statbuf);
Parameters:
- fd: File descriptor of the open file.
- statbuf: Pointer to a struct stat that will hold the file's information.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Useful when the file is already open.
- Doesn't need the file's path, only its file descriptor.

3. lstat() - Get Information about a Symbolic Link


The lstat() system call retrieves file information but does not follow symbolic links.
Instead, it provides information about the link itself.
Syntax:
int lstat(const char *pathname, struct stat *statbuf);
Parameters:
- pathname: Path to the file or symbolic link.
- statbuf: Pointer to a struct stat that will hold the file's information.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
Key Points:
- Useful for inspecting symbolic links themselves.
- Does not resolve the target of the link.
In Linux, the create, open, close, read, write, and lseek system calls are
fundamental for working with files. Here’s a detailed explanation of each:
1. creat() - Create a New File
The creat() system call creates a new file or truncates an existing one to zero
length.
Syntax:
int creat(const char *pathname, mode_t mode);
Parameters:
- pathname: Path to the file to be created.
- mode: File permissions (e.g., `0644`).
Return Value:
- Returns a file descriptor on success.
- Returns -1 on failure.
2. open()- Open a File
The open() system call opens an existing file or creates a new one.
int open(const char *pathname, int flags, ...);
Parameters:
- pathname: Path to the file.
- flags: File access modes (e.g., `O_RDONLY`, `O_WRONLY`, `O_RDWR`,
`O_CREAT`, `O_APPEND`).
- `mode` (optional): Permissions for the file if it is created (e.g., `0644`).
Return Value:
- Returns a file descriptor on success.
- Returns -1 on failure.
3. close() - Close a File
The close() system call closes an open file descriptor.
Syntax:
Parameters:
- `fd`: File descriptor to close.
Return Value:
- Returns 0 on success.
- Returns -1 on failure.
4. read() - Read Data from a File
The read() system call reads data from an open file descriptor into a buffer.
Syntax:
ssize_t read(int fd, void *buf, size_t count);
Parameters:
- fd: File descriptor to read from.
- buf: Buffer to store the read data.
- count: Maximum number of bytes to read.
Return Value:
- Returns the number of bytes read on success.
- Returns 0 for end-of-file (EOF).
- Returns -1 on failure.

5. write()- Write Data to a File


The write() system call writes data from a buffer to an open file descriptor.
Syntax:
ssize_t write(int fd, const void *buf, size_t count);
Parameters:
- fd: File descriptor to write to.
- buf: Buffer containing the data to write.
- count: Number of bytes to write.
Return Value:
- Returns the number of bytes written on success.
- Returns -1 on failure.

6. lseek() - Reposition File Offset


The lseek() system call repositions the file offset for an open file descriptor.
Syntax:
off_t lseek(int fd, off_t offset, int whence);
Parameters:
- fd: File descriptor.
- offset: Offset value to set.
- whence: Reference point (`SEEK_SET`, `SEEK_CUR`, `SEEK_END`).
Return Value:
- Returns the new offset on success.
- Returns -1 on failure.
1. fork() :
Fork() is system call which is used to create new process. New
process created by fork() system call is called child process and
process that invoked fork() system call is called parent process.
Code of child process is same as code of its parent process. Once
child process is created, both parent and child processes start their
execution from next statement after fork() and both processes get
executed simultaneously.

2. vfork() :
Vfork() is also system call which is used to create new process. New
process created by vfork() system call is called child process and
process that invoked vfork() system call is called parent process.
Code of child process is same as code of its parent process. Child
process suspends execution of parent process until child process
completes its execution as both processes share the same address
space.

Exit status of a child process in Linux

It is known that fork() system call is used to create a new process which becomes
child of the caller process.
Upon exit, the child leaves an exit status that should be returned to the parent.
So, when the child finishes it becomes a zombie.
Whenever the child exits or stops, the parent is sent a SIGCHLD signal.
The parent can use the system call wait() or waitpid() along with the macros
WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped
child.
(*)wait() system call : It suspends execution of the calling process until one of its
children terminates.
Syntax of wait() system call:

pid_t wait(int *status);


(*)The waitpid() system call : It suspends execution of the calling process until a
child specified by pid argument has changed state.
Syntax of waitpid() system call :
pid_t waitpid(pid_t pid, int *status, int options)

Note: By default, waitpid() waits only for terminated children, but this behavior is
modifiable via the options argument such as WIFEXITED, WEXITSTATUS etc.
The value of pid can be :

Less than -1 : Meaning wait for any child process whose process group ID is equal
to the absolute value of pid.
Equal to -1 : Meaning wait for any child process.
Equal to 0 : Meaning wait for any child process whose process group ID is equal to
that of the calling process.
Greater than 0 : Meaning wait for the child whose process ID is equal to the value
of pid.

WIFEXITED and WEXITSTATUS are two of the options which can be used to know
the exit status of the child.
WIFEXITED(status) : returns true if the child terminated normally.
WEXITSTATUS(status) : returns the exit status of the child. This macro should be
employed only if WIFEXITED returned true.

fork()
The fork() is one of the syscalls that is very special and useful in
Linux/Unix systems. It is used by processes to create the processes
that are copies of themselves. With the help of such system calls, the
child process can be created by the parent process. Until the child
process is executed completely, the parent process is suspended.

Some of the important points on fork() are as follows.


 The parent will get the child process ID with non-zero value.
 Zero Value is returned to the child.
 If there will be any system or hardware errors while creating
the child, -1 is returned to the fork().
 With the unique process ID obtained by the child process, it
does not match the ID of any existing process group.

exec()
The exec() is such a system call that runs by replacing the current
process image with the new process image. However, the original
process remains as a new process but the new process replaces the
head data, stack data,etc. It runs the program from the entry point by
loading the program into the current process space.

wait()
As in the case of a fork, child processes are created and get executed
but the parent process is suspended until the child process executes.
In this case, a wait() system call is activated automatically due to the
suspension of the parent process. After the child process ends the
execution, the parent process gains control again.

exit()
The exit() is such a function or one of the system calls that is used to
terminate the process. This system call defines that the thread
execution is completed especially in the case of a multi-threaded
environment. For future reference, the status of the process is
captured.

After the use of exit() system call, all the resources used in the process
are retrieved by the operating system and then terminate the process.
The system call Exit() is equivalent to exit().
Signal Handling In Linux Through The signal()
Function
A signal is a message or notification issued to your program by
the operating system or another application (or one of its threads).
Each signal is assigned a number between 1 and 31. Signals are devoid
of argument, and most of the time, their names are self-explanatory.
For instance, signal number 9 or SIGKILL notifies the program that it is
being attempted to be killed.
List of Signals
There is a simple method for compiling a list of all the signals your
system supports.

Simply type the kill -l command to see all the allowed signals.

Types of Signals
 SIGHUP- This signal indicates that the controlling terminal has been
killed. HUP is an abbreviation meaning “hang up.” Locate the
terminal to be controlled or hang up on the control process’s
demise. This signal is obtained when the process is performed from
the terminal and that terminal abruptly terminates.
 SIGINT- This is the signal generated when a user presses Ctrl + C
from the keyboard.
 SIGQUIT- This is the signal generated when a user presses Ctrl + D
from the keyboard.
 SIGILL- Signal for illegal instruction. This is an exception signal
provided by the operating system to your application when it
detects unlawful instruction within your program. For example, if
some code is not understandable by your machine or if your
program’s executable file is corrupted. Another possibility is that
your program loads a corrupted dynamic library.
 SIGABRT- Abort signal indicates that you used the abort() API
within your program. It is used to end a program. abort() generates
the SIGABRT signal, which terminates your program (unless handled
by your custom handler).
 SIGFPE- Exception for floating point numbers. Another exception
signal is generated by the operating system when your program
causes an exception.
 SIGPIPE- Broken pipe. When there is nothing to read on the other
end, write to the pipe.
 SIGSEGV- This is also an exception signal. When a program tries to
access memory that does not belong to it, the operating system
gives that application this signal.
 SIGALRM- Alarm Signal sent through the alarm() system function to
your program. The alarm() system call essentially acts as a timer
that allows you to receive SIGALRM after a set amount of time.
Although there are other timer APIs that are more accurate, this can
be useful.
 SIGTERM- This signal instructs your program to quit. While SIGKILL
is an abnormal termination signal, think of this as a signal to cleanly
shut down.
 SIGCHLD- Informs you that a child’s process of your program has
ended or stopped. This is useful if you want to synchronize your
process with one that has children.
 SIGUSR1 and SIGUSR2- SIGUSR1 and SIGUSR2 are two undefined
signals that are provided for your consideration. These signals can
be used to communicate with or synchronize your software with
another program.
Signal as interrupt
 Signals disrupt your program in addition to being instructive.
 For example, one of the threads in your application must briefly
switch to signal handler mode in order to process a signal.
 As of the Linux kernel version 2.6, it should be noted that most
signals only interrupt one thread, as opposed to the previous
practice of interrupting the entire application.
 Additionally, a signal handler itself may be halted by a different
signal.

Signal Sets
Linux provides mechanisms for managing sets of signals, such as blocking,
unblocking, or waiting for signals using:
sigset_t: A data type representing a set of signals.
Functions: sigemptyset, sigfillset, sigaddset, sigdelset, sigismember.
Functions and Concepts
kill
Function: int kill(pid_t pid, int sig)
- Sends a signal to a process or a group of processes.
- pid > 0: Sends the signal to the process with the specified PID.
- pid = 0: Sends the signal to all processes in the same group as the caller.
- pid = -1: Sends the signal to all processes the caller has permission to send
signals to.
- pid < -1: Sends the signal to all processes in the specified group.

raise
- Function: int raise(int sig)
- Sends a signal to the calling process.
- Essentially, it's a wrapper around kill(getpid(), sig).
alarm
- Function: unsigned int alarm(unsigned int seconds)
- Schedules a SIGALRM signal to be sent to the calling process after the specified
number of seconds.
- Cancels a previously set alarm if seconds is 0.
pause
- Function: int pause(void)
- Suspends the calling process until a signal is delivered.
abort
- Function: void abort(void)
- Causes the process to terminate abnormally by sending itself the SIGABRT signal.
- Generates a core dump for debugging.
system
- Function: int system(const char *command)
- Executes a shell command by invoking /bin/sh.
- Waits for the command to complete and returns its exit status.
- Handles signals such as SIGINT and SIGQUIT.
sleep
- Function: unsigned int sleep(unsigned int seconds)
- Suspends execution of the calling process for the specified number of seconds.
- Can be interrupted by a signal.
This combination of functions and signals is critical for process control, inter-
process communication, and error handling in Linux.

semget: Creates or retrieves a semaphore set.


semop: Performs operations (increment, decrement, wait) on semaphores.
semctl: Controls semaphore attributes and performs operations like initialization
or deletion.
msgget: Creates or accesses a message queue.
msgsnd: Sends a message to a queue.
msgrcv: Retrieves a message from a queue.
msgctl: Manages message queues, e.g., delete or query attributes.
shmget: Allocates or accesses shared memory segments.
shmat: Attaches shared memory to a process.
shmdt: Detaches shared memory from a process.
shmctl: Performs operations like removal or querying shared memory attributes.
These are essential for managing IPC via semaphores, message queues, and
shared memory.

You might also like