Unixxxx 1
Unixxxx 1
execution process are dependent on the file. - buf: Pointer to a struct stat to
operating system.# In the following the store file status information.5. **lseek:*
process data structure of operating system - *Purpose:* Moves the file pointer to a
in the unix system as shown in the figure. specified location. - *Syntax:* off_t
A Unix process consist of three segments lseek(int fd, off_t offset, int whence); -
1) text segment 2) data segment 3)stack *Parameters:* - fd: File descriptor. -
segment. 1) text segment consist of text offset: Number of bytes to move the ile
elements, programs, text in machine pointer. - whence: Reference point for the
executable instructions code format. 2) offset .6. **fstat:** - *Purpose:*
data segment contains static and local Retrieves file status information using a
variables 3) stack segment contain file descriptor. - *Syntax:* int fstat(int fd,
runtime variables and return address of all struct stat *buf); - *Parameters:* - fd:
active function for a process. #Unix kernel File descriptor. - buf: Pointer to a struct
has a process table contains pointers to stat to store file status information.7.
the text,data stack segments and the u- **read:** - *Purpose:* Reads data from
area of a process.#The u-area is an a file. - *Syntax:* ssize_t read(int fd, void
extension of a process table entry and *buf, size_t count); - *Parameters:* - fd:
contains other process such as file File descriptor. - buf: Buffer to store the
descripter table current root director and read data. - count: Number of bytes to
inode number. read.8. **close:** - *Purpose:* Closes a
file descriptor. - *Syntax:* int close(int fd);
M2-1. **open:** - *Purpose:* Opens a - *Parameters:* - fd: File descriptor to be
file or creates it if it doesn't exist. - closed..
*Syntax:* int open(const char *path, int
flags, mode_t mode); - *Parameters:* - *Memory Allocation:*1. **malloc
path: Path to the file. - flags: Flags (Memory Allocation):** It is also called as
specifying the mode of opening . - mode: memory allocation method in c with
Permissions for the file (used if the file is allocate a special number of bytes of
created).2. **write:** - *Purpose:* memory. #If the allocation fails, returns
Writes data to a file. - *Syntax:* ssize_t NULL. - *Prototype:- void* malloc(size_t
write(int fd, const void *buf, size_t count); size);2. **calloc (Contiguous
- *Parameters:* - fd: File descriptor. - Allocation):** - *Prototype:* void*
buf: Buffer containing data to be written. calloc(size_t num, size_t size); . # Allocates
- count: Number of bytes to write.3. memory for an array of elements, each
**fcntl:** - *Purpose:* Performs various with a specified size. # Initializes all the
operations on a file descriptor. - *Syntax:* bytes to zero.# Returns a pointer to the
int fcntl(int fd, int cmd, ... /* arg */ ); - beginning of the allocated memory
*Parameters:* - fd: File descriptor. - block.#If the allocation fails, returns
cmd: Command specifying the operation. NULL.3. **realloc (Reallocate Memory):*
- Additional arguments based on the - *Prototype:- void* realloc(void* ptr,
command.4. **stat:** - *Purpose:* size_t size); #Realloc() method which
Retrieves file status information. - increase or decrease the size of an
*Syntax:* int stat(const char *path, struct allocated area.# this method change the
size of an alcotted memory block.# this address space .#vfork() function call is less
method should only be used for used.. C Program Demonstrating fork and
dynamically allocated memory.#If the vfork: #include <unistd.h>#include
allocation fails, returns NULL.4. **free <stdio.h>#include <stdlib.h>#include
(Free Allocated <sys/types.h>#include <sys/wait.h>int main() {
Memory):**-.*Prototype:*- void pid_t pid, vpid; // Demonstrate fork @pid =
fork();@ if (pid == -1) {@ perror("Fork
free(void* ptr); …#Deallocates the
failed");@ exit(EXIT_FAILURE);@ } else if (pid
memory block previously allocated by
== 0) { @ // Child process @ printf("Child
malloc, calloc, or realloc. #The pointer ptr process (PID: %d)\n", getpid()); @
should point to the beginning of a valid exit(EXIT_SUCCESS); @ } else { @ // Parent
allocated block.# After freeing, the pointer process @ wait(NULL); @ }.. // Demonstrate
becomes invalid, and the memory can be vfork vpid = vfork(); @ if (vpid == -1) { @
reused. perror("vfork failed");@ exit(EXIT_FAILURE);
@ } else if (vpid == 0) { @ // Child process in
M3-Fork ():- #An existing process can vfork @ printf("Child process (vfork) (PID:
create a new one by calling fork() %d)\n", @ getpid()); @ _exit(EXIT_SUCCESS);
function.#here two condition for parent @ } else { @ // Parent process in vfork @
and child.i) both parent and child process wait(NULL); @ } @ return 0;..
run child.ii) parent will wait till the child
There are 6 exec functions:- #include
executes its process. #the parent process
<unistd.h> # int execl(const char pathname,
uses fork to create a child process. # after const char *arg0,... / (char *)0 */ );# int
fork executes the parent and child process execv(const char *pathname, char *const argv
have different Pid's and ppid's. #when a []);# int execle(const char pathname, const
process is forked the child inherits the char *arg0,... /(char *)0, char *const envp
attributes of the parent.#child run it own */ );#int execve(const char pathname, char
address space changes mode to these *const argv[], char *const envp[]); #int
parameters don't affect the parent. #when execlp(const char *filename, const char *arg0,
fork is invoked the canal repeated the ... / (char *)0 */ );# int execvp(const char
kernel repticates address space of parent *filename, char *const argv []);..
process to the child process. #the fork is M3- A race condition occurs when multiple
responsible for the multiplication of processes are trying to do something with
process in the system. #prototype of fork shared data and the final outcome depends
is:- #include<unistd.h>/pid_tfork(void); on the order in which the processes run.
#include <sys/type.h>/static void
2)vfork:- #an existing process can created charatatime(char *); /int main(void)/{ / pid_t
a new process is called vfork .#vfork pid; / if ((pid = fork()) < 0) / { / err_sys("fork
creates a child process that is a new error"); / } / else if (pid == 0) / { /
process and it blocks a parent process. charatatime("output from child\n"); /} /
#Vfork() has the same calling sequence else / { / charatatime("output from parent\
and same return values as fork. # the n"); / } / exit(0); / } / static void
vfork() creates the new prcess, just like charatatime(char *str) / { / char
*ptr; /Int c; / setbuf(stdout, NULL);
fork without copying the address space of
for (ptr = str; (c = *ptr++) != 0; ) / putc(c,
the parent into the child.#the vfork system
stdout); / }…
call child and parent process share same
address spaces.#there is no cuastage of
gracefully...\n"); / exit(EXIT_SUCCESS); //
Exit the program gracefully /
M4-Signals are software interrupts sent
to a process to notify it that a specific } / int main() { @ // Set up the handler for
event has occurred. These events can timeout (SIGALRM) / signal(SIGALRM,
range from simple notifications to handleTimeout); @ // Set up the handler
requests for a process to terminate.The for interrupt (SIGINT) / signal(SIGINT,
function prototype of the signal API is: handleInterrupt);/ // Set an alarm for 5
#include <signal.h>/ void (*signal(int seconds / alarm(5);/ printf("Waiting for
sig_no, void (*handler)(int)))(int); signals...\n");/ // Keep the program
running/ while (1) {/ // Do nothing, just
Four Common Signals: SIGINT wait for signals/ sleep(1);/ }/ return 0;/}..
(Interrupt):Sent to a process when the
user presses Ctrl+C. Typically used to M4-explain Unix system support for signals-
interrupt or terminate a running process Certainly! Here are small points explaining
Unix system support for signals:1.
gracefully. SIGALRM (Alarm Clock):Used
*Definition:*- Signals are software interrupts
to set a timer. It is often employed to
used for interprocess communication and
schedule tasks or to implement timeout process management in Unix-like operating
functionality. SIGTERM(Termination):Sent systems.2. *Signal Numbers:* - Each signal is
to a process to request termination. identified by a unique integer called a signal
Allows the process to perform cleanup number (e.g., SIGINT has signal number 2).3.
before exiting. SIGHUP *Signal Generation:* - Signals can be
(Hangup):Historically associated with generated by the kernel, user processes, or
terminal sessions. Sent to a process when other sources such as hardware events.4.
the controlling terminal is closed or the *Signal Handling:* - Processes can define how
session leader exits. SIGKILL (Kill): Sent to they handle signals by establishing signal
handlers, which are functions executed in
a process to forcefully terminate it. Unlike
response to specific signals.5. *Default
SIGTERM, SIGKILL cannot be caught or
Actions:* - Each signal has a default action
ignored by the process. It immediately
associated with it, such as terminating the
terminates the process without allowing it process, stopping it, or ignoring the signal.
to perform any cleanup actioSns. A
program to set up signals handler for
SIGALRM and SIGINT signals.#include
<stdio.h> /#include <stdlib.h>/ #include
<signal.h> / #include <unistd.h>
// Function to handle timeout signal
(SIGALRM) / void handleTimeout(int
signum) { / printf("Oops! Time's up!\
n");exit(EXIT_SUCCESS); // Exit the
program gracefully }. // Function to
handle interrupt signal (SIGINT)/ void
handleInterrupt(int signum) { /
printf("Received Ctrl+C. Exiting
Crashes: The server catches SIGPIPE to
handle cases where a client sends a
request and terminates before reading the
response. This prevents issues with
M5-3) What is FIFO? With a neat diagram, lingering client-specific FIFOs in the file
explain the client-server communication using system.
FIFO. FIFO (First-In-First-Out): A FIFO, or
M5-Message queue- A message queue is
named pipe, is a method of interprocess
a mechanism for inter-process
communication (IPC) in Unix-like operating
communication that allows processes to
systems. It provides a way for processes to
exchange messages with each other. In
communicate with each other by using a
this context, messages are data packets
special file as a conduit for data
that contain information to be shared
transmission .. Creation with mkfifo:
between different processes. System
Created using mkfifo to establish a named
calls used for message queues(WRITE 2-3
pipe in the file system. Example: mkfifo
PROTOTYPE) ftok(): is use to generate a
myfifo. Opening with open: Opened using
unique key. msgget(): either returns the
open for read-only (O_RDONLY) or write-
message queue identifier for a newly
only (O_WRONLY). Example: int fd =
created message queue or returns the
open("myfifo", O_RDONLY); Blocking and
identifiers for a queue which exists with
Nonblocking: In the normal case, an open
the same key value. msgsnd(): Data is
for read-only or write-only blocks until
placed on to a message queue by calling
another process opens the
msgsnd(). msgrcv(): messages are
complementary end. If O_NONBLOCK is
retrieved from a queue. msgctl(): It
specified, nonblocking behavior is
performs various operations on a queue.
enabled. The client-server
Generally it is use to destroy message
communication using FIFO # Well-
queue . Semaphore- A semaphore is a
Known FIFO. #Unique FIFO for Each Client:
synchronization mechanism used to
Each client includes its process ID with
control access to shared resources in a
the request. The server creates a unique
multi-process or multi-threaded
FIFO for each client using a pathname
environment. It involves a counter that
based on the client's process ID.
determines the availability of a resource,
Example: /vtu/ser.XXXXX, where XXXXX is
and processes must follow specific steps
replaced with the client’s process ID.
to obtain and release access to the shared
Server Reads Requests: The server
resource. Semaphore Creation (semget):
continuously reads requests from the well-
Creates a new semaphore set or
known FIFO. Server Processes
references an existing one. Example: int
Requests: For each request, the server
semid = semget(IPC_PRIVATE, 1,
processes the client's task or query.
IPC_CREAT | 0666). Semaphore
Server Writes Responses: The server Initialization (semctl): Performs various
writes responses back to the unique FIFO operations on a semaphore set, including
created for each client. The unique FIFO initialization. Example: union semun arg;
ensures that clients can distinguish their arg.val = 1; // Set semaphore value to 1 int
responses from others. Handling Client result = semctl(semid, 0, SETVAL, arg); Here,
the semaphore set identified by semid is flexibility in organizing the file system.4.
initialized with a value of 1 using the SETVAL **Character Devices (c):* - Represented by a
command. c. - Correspond to devices that transfer data
character by character. - Examples include
M1-Ansic and k and RC :-1)standardization-
terminals, serial ports, or any device that
*ansic #follow the ansic based on the origin
operates on a character-by-character basis.5.
kernighan and ritchiebon.2) function
**Block Devices (b):** - Represented by a b.-
prototype:-#support function photo does not
Correspond to devices that transfer data in
support function prototype.3) header file:-
fixed-size blocks or chunks. - Examples
#introduces new headder files like<std def.h>
include hard drives, SSDs, or any device that
#free introduces on traditional header file.4)
operates on a block-by-block basis.8. *Domain
data types:-#introduces new data type like
Sockets:* - Special type of socket used for
void.#limited data types compared to ansic. 5)
communication between processes on the
standard I/o:- #user standardised I/o
same machine. - Represented by a S.
functions. #i/o functions are less standardized.
6) function declaration:-#expect function M3- Discuss exit functions;-
declaration#function declaration not
exit() Function: The exit() function is part of
mandatory.7) library function:-
#comprehensive standard library .#future the C standard library and is used to
standard library. terminate a program. Its prototype is: void
exit(int status);.# where status is an
M1- Ansi c and c++ 1)paradigm:-#procedure integer value that serves as the program's
programming language.#multi paradigm
exit status. #When a program calls exit(),
( procedural and object oriented).2)
it immediately terminates, and the control
inheritance:-#not supported #supports both
compiler time and runtime polymorphism.3)
returns to the operating system along with
object§ class:-#ns #support.4) polymorphism:- the specified exit status.# The exit status
#ns#support.5) function overloading:-#ns.6) is typically used to convey information
operator overloading:-#ns.7) standard about the program's execution to the
template library:-#ns#includes the standard calling process or shell. A status of 0
template library.8) memory management:- usually indicates successful
#manual (malloc, free)#supports constructors, execution.Example: #include
destruction new and delete.8) header file:- <stdlib.h>/int main() {@ // Program
#typically use h extension.#no h ext in header logic@ // Exit with status 0 indicating
files.9) ex:- #int tool..);#int fool(void); successful execution@ exit(0); @ }
M1- The unix file types in Unix m1;-:discuss directory file:--1.
include: 1. **Regular Files (-):** - Representation: - Represented by a d as the
Represented by a hyphen -. - Contain data first character in the output of the ls -l
organized in a specific format. - Examples command, indicating that it is a directory. -
include text files, binary files, and program Example: drwxr-xr-x 2 user group 4096 Mar 11
executables.2. **Directories (d):** - 10:30 my_directory 2. Purpose: - Directories
Represented by a d. - Contain entries that are used to organize and hierarchically
point to other files or directories. - Directories structure files in a file system.- They provide
provide a hierarchical organization of files in a a means to group related files and directories
file system.3. **Symbolic Links (l):**- together.4. Navigation - Users navigate the
Represented by an l.. - Point to another file or file system by moving in and out of
directory, acting as a reference or shortcut. directories using commands like cd (change
- Symbolic links enable file sharing and
directory). - Paths specify the location of a
file or directory within the directory tree.