0% found this document useful (0 votes)
6 views

USP Solved Model QP AMRUTA

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

USP Solved Model QP AMRUTA

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIX SYSTEM PROGRAMMING (BCS515C)

SOLVED MODEL QUESTION PAPER (2022 SCHEME)

MODULE 1

Q.01. A). With the example, explain the following commands. i)man ii)pwd iii)od iv) cal
v)date.
Ans:
i. Man:
The man command in UNIX/Linux is used to display the manual pages of other
commands, utilities, or programs.
It provides detailed documentation, including a description, options, usage examples,
and additional information.
Syntax:
man [section] command
Example:
Basic Example:
To learn about the ls command:
man ls
This will display the manual page for ls, showing its description, options, and usage.

ii. pwd: Checking your current directory


User can move around from one directory to another, but at any point of time, if user
wants to find out in which directory he is present then user can use Print Working
Directory(pwd) command.

Ex:pwd

/home/kumar/SantoshReddyP

pwd also displays the absolute pathname.

iii. od: Displaying Data in Octal


od command displays the contents of executable files in a ASCII octal value.
 $ more ofile this file is an example for od command ^d used as an interrupt
key
 -b option displays this value for each character separately.
 Each line displays 16 bytes of data in octal, preceded by the offset in the file
of the first byte in the line.

Eg: $ od –b file
0000000 164 150 151 163 040 146 151 154 145 040 151 163 040 141 156 04
0000020 145 170 141 155 160 154 145 040 146 157 162 040 157 144 040 143
0000040 157 155 155 141 156 144 012 136 144 040 165 163 145 144 040 141

Dept of CSE, SIT, KLB. Page 1


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

0000060 163 040 141 156 040 151 156 164 145 162 162 165 160 164 040 153
0000100 145 171

iv. cal : The calendar-


Using cal command it is possible to see the calendar of specific month.
Syntax: $cal [[month] year]
Arguments are optional here. So ‘cal’ can be used without arguments.
Eg: $cal //displays the calendar of current month
Eg: $cal 03 2006 Displays calendar of march 2006.
When ‘cal’ is used with arguments month is optional but year is mandatory. A single
argument to cal is interpreted as year.
v. date : to display date and time
The Unix system maintains an internal clock meant to run perpetually. When the
system isshut down a battery backup keeps the clock ticking.
Date command is used to display bothand time as follows:
Eg: $date
Tue Aug 28 1:58:03 IST 2018
Date displays 6 fields of output:
1. day 2.Month name 3. Date 4.time 5.time zone 6.year
To extract individual fields we can use following options with date

Dept of CSE, SIT, KLB. Page 2


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

B .With a neat diagram, explain the kernel and shell relationship in UNIX operating
System?

The main concept in the unix architecture is the division of labor between two
agencies the KERNEL and SHELL. The kernel interacts with hardware and shell
interacts with user. The kernel is the core of the operating system- a collection of
routines mostly written in C. It is loaded into memory when the system is booted and
communicates directly with the hardware. User applications (programs) that need to
access the hardware, uses the services of kernel. These programs access the kernel
through a set of function called system calls. Apart from providing support to user
programs, the kernel also performs other tasks like managing system’s memory,
scheduling processes, decides their priorities etc. So the kernel is often called the
operating system- a program’s gateway to the computer’s resource. The shell is the
command interpreter, it translates command into action. It is the interface between
user and kernel. System contains only one kernel, but there may be several shells.
When user enters a command through the keyboard the shell thoroughly examines
keyboard input for special characters, if it finds any, it rebuilds simplified command
line and finally communicates with kernel to see that the command is executed.For
eg,consider a echo command which has lots of spaces between the arguments: Eg:
$echo Sun solaris In the above example shell first rebuilds the command line i.e. it
will compress all extra spaces, then it will produces output.

Sun solaris.

Dept of CSE, SIT, KLB. Page 3


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Q.02. a) .Explain the salient features of Unix Operating System.

Ans: Features of UNIX:

1. Multi-user system:
 Unix is a multi-user system i.e. multiple user can use the system at a
time,resources are shared between all users.
 In unix systems, computer breaks up a unit of time into several segments. So
at any point in time, the machine will be doing the job of a single user.
 The moment the allocated time expires, the previous job will be preempted
and next user’s job is taken up.
 This process goes on until clock has turned full circle and the first user’s job is
taken up once again.Unix is a multi-programming
 system, it permits multiple programs to run. This can happen in two ways:

Multiple user can run separate jobs.


A single user can also run multiple jobs.

2. Multi-tasking system:

A single user can run multiple tasks concurrently, in multitasking environment


a user sees one job running in the foreground, the rest running in the background.
It is possible to switch the job between background and foreground, suspend or even
terminate them.

3. Building block approach:

 Unix contains several commands each performs one simple job.


 It is possible to connect different with the pipe (|) to get different jobs done.
 The commands that can be connected in this way are called filters, because
they filter or manipulate data in different way.
 for ex: ls command lists all files.wc command counts the number of words .
 They can be combined using pipes(|) to find the total number of files in
thedirectory.

4. Unix tool kit:


Unix contains set of tools like general purpose tools, text manipulation utilities
(called filters), compilers, interpreters, networked application and system administration
tools.
5. Pattern matching:

Dept of CSE, SIT, KLB. Page 4


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Unix contains pattern matching features, using this features it is possible to match the
different strings.
Eg: ‘*’$ls chap*
Here ‘*’ is the special character, which matches the filename, which starts with ‘chap’.

6. Programming facility:

Unix shell is also a programming language. It has control structures, variables,loops


that establish it as a powerful programming language. This features can be usedto
design a shell scripts.

7. Documentation:
Unix contains ‘man’ pages for each command, it contains references for
commands and their configuration files.Apart from man page, we can
even get thecommand information in internet.there are severalnewsgroups on unix
where we canfire our queries to get the solution to a problem.

b). Differentiate between Internal and External commands in UNIX operating system
with example.
Ans:Internal and external commands:
 External commands will have independent existence in one of the directories
specified in the PATH variable.
 Eg: $ls
 ls is /bin/ls
o ‘ls’ command having an independent existence in the /bin directory (or
/usr/bin). So‘ls’ is a external command.
 Internal commands doesn’t have independent existence, they are shell built-ins.
 Eg: $type echo
o echo is a built-in.
 Shell is an external command with difference, i.e. shell possesses its own set
ofinternalcommands.
 If a command exists both as an internal command of the shell as well asan external
one, the shell will give top priority to its internal command.
 Eg: echo command, which is also found in /bin directory but rarely ever
executed,because the shell makes sure that the internal echo command takes
precedence over theexternal.

Dept of CSE, SIT, KLB. Page 5


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

MODULE-2

Q.03 .a.) Explain ls Command with all the options.


Ans:The ls command with options:
The ls command is to obtain a list of all file names in the current directory.
Eg: ls –l
ls –l -a

b.) Define Wild Cards? Explain various shell wild cards with suitable example.
Ans: Wild Cards: In UNIX system programming Wild cards are special characters used to
represent one or more characters in file names, allowing users to specify patterns instead of
exact filenames.
The meta characters that are used to construct the generalized pattern for matching filenames
belong to a category called wild-cards.
The following table lists them:

Dept of CSE, SIT, KLB. Page 6


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Examples:
To list all files that begin with chap, use, $ls chap*
To list all files whose filenames are six character long and start with chap, use , $ls chap??
$ ls .???*
However, if the filename contains a dot anywhere but at the beginning, it need not be
matched explicitly.

Q.04. a). Explain changing file permissions in relative and absolute manner.
Ans:Changing File Permission:
 Relative Permissions:
• chmod only changes the permissions specified in the command lineand leaves the other
permissions unchanged.
• Its syntax is:
chmod category operation permission filename(s)
• chmod takes an expression as its argument which contains:
• user category (user, group, others).
• operation to be performed (assign or remove a permission).
• type of permission (read, write, execute).

• Category : u – user g – group o – others a - all (ugo)


• operations : + assign - remove = absolute
• permissions: r – read w – write x - execute

Example:

Dept of CSE, SIT, KLB. Page 7


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

• Initially,
-rw-r—r-- 1 kumar metal 1906 sep 23:38 xstart
$chmodu+xxstart
-rwxr—r-- 1 kumar metal 1906 sep 23:38 xstart
• The command assigns (+) execute (x) permission to the user (u),other permissions
remain unchanged.
$chmodugo+xxstart or chmoda+xxstart or chmod +x
xstart
$ls –l xstart
-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

 Absolute Permissions:
• Here, we need not to know the current file permissions. We can setall nine permissions
explicitly. A string of three octal digits is usedas an expression.
The permission can be represented by one octaldigit for each category. For each category, we
add octal digits.
If werepresent the permissions of each category by one octal digit, this
is how the permission can be represented:

Read permission – 4 (octal 100)


Write permission – 2 (octal 010)
Execute permission – 1 (octal 001

Using absolute permission, we have:


$chmod 666 xstart
Dept of CSE, SIT, KLB. Page 8
UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

$chmod 644 xstart


$chmod 761 xstart
• will assign all permissions to the owner, read and writepermissions for the group and only
execute permission to theothers.
• 777 signify all permissions for all categories, but still we canprevent a file from being
deleted.
• 000 signifies absence of all permissions for all categories, but stillwe can delete a file.
b. Explain if and While control statements in shell scripts with suitable program.
Ans:
 The if conditional:
The if statement makes two-way decisions depending on the fulfillment of acertain
condition. In the shell, the statement uses the following forms:

Example:
#!/bin/sh
#Shell script to illustrate
if conditional if grep 'director' emp.lst
then
echo “Pattern found in File!”
else
echo “Pattern not-found in File!”
fi
 While Looping:
 A while loop is different from a for loop in that is uses a test condition to determine
whether or not to execute its command block.
 As long as thecondition returns true when tested, the loops executes the commands.
 If it returns false, the script skips the loop and proceeds beyond its terminate point.
Consequently, the command set could conceiveably never
run.
 This is further illustrated by the loop’s syntax:

Dept of CSE, SIT, KLB. Page 9


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Syntax:
while condition
do
command1
.
.
.
commandn
done
After performing the last command in the block, the loop starts tests thecondition again &
determine whether to proceed beyond the loop or failthrough it once more.
Example:
Here is the example that uses while loop to open through the given list
of numbers:
i=1
while [ $i -le 5 ]
do
echo $i
i=`expr $i + 1`
done
this will produce following result:
1
2
3
4
5

Dept of CSE, SIT, KLB. Page 10


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

MODULE-3

Q.05 a) Explain the following functions with their prototypes and examples: i) mkdir()
ii) rmdir() iii)fcntl().
Ans:
 mkdir():
Directories are created with the mkdir and mkdirat functions, and deleted with the
rmdir function.

#include <sys/stat.h>
int mkdir(const char *pathname, mode_t mode);

return: 0 if OK, −1 on error

 This function create a new, empty directory. The entries for dot and dot-dot
are created automatically. The specified file access permissions, mode, are
modified by the file mode creation mask of the process.
 A common mistake is to specify the same mode as for a file: read and write
 permissions only. But for a directory, we normally want at least one of the
execute bits enabled, to allow access to filenames within the directory.

 rmdir():
An empty directory is deleted with the rmdir function. Recall that an emptydirectory
is one that contains entries only for dot and dot-dot.

#include <unistd.h>
int rmdir(const char *pathname);

Returns: 0 if OK, −1 on error

 If the link count of the directory becomes 0 with this call, and if no other
process has thedirectory open, then the space occupied by the directory is
freed.
 If one or moreprocesses have the directory open when the link count reaches
0, the last link isremoved and the dot and dot-dot entries are removed before
this function returns.
 Additionally, no new files can be created in the directory. The directory is not
freed,however, until the last process closes it.

 fcntl():

Dept of CSE, SIT, KLB. Page 11


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

 The fcntl function can change the properties of a file that is already open.
 The fcntl function helps a user to query or set flags and the closeon-exec flag of any
file descriptor.
 The prototype of fcntl is:

#include <fcntl.h>
int fcntl(int fdesc, int cmd, …..);
 The first argument is the file descriptor.
 The second argument cmd specifies what operation has to be performed.
 The third argument is dependent on the actual cmd value.
 The possible cmd values are defined in header.
 The fcntl function is useful in changing the access control flag of a file descriptor.
 For example: after a file is opened for blocking read-write access and the process
needs to change the access to non-blocking and in writeappend mode, it can call:

int cur_flags=fcntl(fdesc,F_GETFL);
int rc=fcntl(fdesc,F_SETFL,cur_flag | O_APPEND | O_NONBLOCK);

b). Discuss the various UNIX system implementations?


Ans:
Implementations of UNIX Systems
The UNIX system has evolved through various implementations adhering to standards like
ISO C, IEEE POSIX, and the Single UNIX Specification. These standards define system
interfaces that vendors use to build practical systems. UNIX's journey began with the 6th
Edition (1976) and 7th Edition (1979) on PDP-11, widely distributed versions that led to
three branches:

AT&T's Commercial Versions: Led to System III and System V for business use.
Berkeley UNIX (BSD): Developed at UC Berkeley, known for innovations like TCP/IP
networking.
Research Versions: Advanced systems developed at Bell Labs, ending with the 10th Edition
(1990).
UNIX System V Release 4 (SVR4), released by AT&T in 1989, merged features from
System V Release 3.2, SunOS, 4.3BSD, and Xenix, conforming to the POSIX 1003.1
standard. AT&T also introduced the System V Interface Definition (SVID) to define
compliance.

Berkeley Software Distribution (BSD): Key versions include 4.2BSD (1983) and 4.3BSD
(1986) for VAX minicomputers, followed by 4.4BSD-Lite (1994) and 4.4BSD-Lite Release 2
Dept of CSE, SIT, KLB. Page 12
UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

(1995), which were free from AT&T restrictions. Development spanned platforms like PDP-
11, VAX, and 80386 PCs, leading to 386BSD.

FreeBSD: Based on 4.4BSD-Lite, FreeBSD was created to continue the BSD legacy and
offers software in both binary and source formats, ensuring openness and accessibility.

Linux: Created by Linus Torvalds in 1991, Linux is a free operating system under the GNU
Public License, known for rapid hardware support. Examples in this book used Ubuntu 12.04,
with the 3.2.0 kernel.

Mac OS X: Built on the Darwin core, combining the Mach kernel, FreeBSD, and object-
oriented frameworks. Certified as a UNIX system since version 10.5, examples were tested
using Mac OS X 10.6.8 (Darwin 10.8.0).

Solaris: Developed by Sun Microsystems (now Oracle), Solaris is based on System V Release
4, enhanced for 15 years, and certified as a UNIX system. Sun released most of its code as
OpenSolaris in 2005 to build a developer community. Examples were tested using Solaris 10.

These systems highlight the evolution of UNIX and its adaptations across platforms and
communities.

Q.06 .a) With a neat diagram explain how a C program is started and terminated.
Ans:
main Function:

 A C program starts execution with a function called main.


 The prototype for the main function is:
int main(int argc, char *argv[]);
 where argc is the number of command-line arguments, and argv is an array of pointers
to the arguments.
 When a C program is executed by the kernel by one of the exec functions, a special
start-up routine is called before the main function is called.

Dept of CSE, SIT, KLB. Page 13


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

 The executable program file specifies this routine as the starting address for the
program;
 This start-up routine takes values from the kernel, the command-line arguments and
the environment and sets things up so that the main function is called.
Exit Functions:
 Three functions terminate a program normally: _exit and _Exit, which return to the
kernel immediately, and exit, which performs certain cleanup processing and then
returns to the kernel.
#include<stdlib.h>
void exit(int status);
void _Exit(int status);
#include <stdlib.h>
void _exit(int status);
 All three exit functions expect a single integer argument, called the exit status.
 Returning an integer value from the main function is equivalent to calling exit with
the same value. Thus exit(0) is the same as return(0) from the main function.
 In the following situations the exit status of the process is undefined.

✓ any of these functions is called without an exit status.

✓ main does a return without a return value.

✓ main “falls off the end”, i.e if the exit status of the process is undefined.
Example:
$cc Pgm.c
$./a.out hello, world
$echo $? // Print the exit status.
The following figure summarizes how a C program is started and the various
ways it can terminate.

Dept of CSE, SIT, KLB. Page 14


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

b). Explain getrlimit () and setrlimit() API’s.


Ans: getrlimit & setrlimit Functions:
 Every process has a set of resource limits, some of which can be queried and changed
by the getrlimit and setrlimit functions.

#include <sys/resourse.h>
int getrlimit(int resource, struct rlimit *rlptr);
Int setrlimit(int resource, const struct rlimit *rlptr);

 Both return: 0 if OK, nonzero on error.


 Each call to these two functions specifies a single resource and a pointer to the
following structure:
struct rlimit
{
rlim_trlim_cur; //soft limit: current limit
rlim_trlim_max; //hard limit: maximum value for rlim_cur
}
 Three rules govern the changing of the resource limits.

✓ A process can change its soft limit to a value less than or equal to its hard limit.

✓ A process can lower its hard limit to a value greater than or equal to its soft limit.
This lowering of the hard limit is irreversible for normal users.

✓ Only a superuser process can raise a hard limit.

Dept of CSE, SIT, KLB. Page 15


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

MODULE-4

Q.07. a) Explain the fork and vfork system calls. How does fork differ from vfork?
Ans:
fork FUNCTION :
An existing process can create a new one by calling the fork function.
#include <unistd.h>
pid_t fork(void);
Returns: 0 in child, process ID of child in parent, 1 on error.
 The new process created by fork is called the child process.
 This function is called once but returns twice.

 The only difference in the returns is that the return value in the child is 0, whereas the
return value in the parent is the process ID of the new child.
 The reason fork returns 0 to the child is that a process can have only a single parent, and the
child can always call getppid to obtain the process ID of its parent.
 Both the child and the parent continue executing with the instruction that follows the call to
fork.  The child is a copy of the parent
Example programs:
Program 1
/* Program to demonstrate fork function Program name – fork1.c */
#include <sys.types.h>
#include<unistd.h>
int main( )
{
fork( );
printf(“\n hello USP”);
}
Output :
$ cc fork1.c

Dept of CSE, SIT, KLB. Page 16


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

$ ./a.out
hello USP
hello USP
vforkFUNCTION :
 The function vfork has the same calling sequence and same return values as fork.
 The vfork function is intended to create a new process when the purpose of the new
process is to exec a new program.
 The vfork function creates the new process, just like fork, without copying the address
space of the parent into the child, as the child won't reference that address space; the
child simply calls exec (or exit) right after the vfork.
 Instead, while the child is running and until it calls either exec or exit, the child runs
in the address space of the parent. This optimization provides an efficiency gain on
some paged virtual-memory implementations of the UNIX System.
 Another difference between the two functions is that vfork guarantees that the child
runs first, until the child calls exec or exit. When the child calls either of these
functions, the parent resumes.
 Example of vfork function:
#include "apue.h"
int glob = 6;
int main(void) { int var;
pid_tpid; var = 88; printf("before vfork\n");
if ((pid = vfork()) < 0) { err_sys("vfork error");
}
else if (pid == 0) {
var++; _exit(0);
}
printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var); exit(0);
}
Output:
$ ./a.out
before vfork
pid = 29039, glob = 7, var = 89

Dept of CSE, SIT, KLB. Page 17


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

b) Write short notes on the following with examples: i) exec() ii) Race conditions.
Ans: I : exec():
When a process calls one of the exec functions, that process is completely replaced by
thenew program, and the new program starts executing at its main function.
The process ID does not change across an exec, because a new process is not created;
exec merely replaces the current process - its text, data, heap, and stack segments -
with a brand new program from disk.

Example of exec functions:


#include "apue.h"
#include
Char *env_init[] = { "USER=unknown", "PATH=/tmp", NULL };
int main(void)
{
pid_tpid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* specify pathname, specify environment */
if (execle("/home/sar/bin/echoall", "echoall", "myarg1", "MY ARG2", (char *)0,
env_init) < 0)
err_sys("execle error");
} if (waitpid(pid, NULL, 0) < 0) err_sys("wait error");
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) {
if (execlp("echoall", "echoall", "only 1 arg", (char *)0) < 0) err_sys("execlp error");
}
exit(0);
}
Output: $ ./a.out
argv[0]: echoall
argv[1]: myarg1
argv[2]: MY ARG2
USER=unknown
PATH=/tmp
$ argv[0]: echoallargv[1]:
only 1 arg USER=sar
LOGNAME=sar
SHELL=/bin/bash 47 more lines that aren't shown
HOME=/home/sar

I. Race conditions:

Dept of CSE, SIT, KLB. Page 18


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

A race condition occurs when multiple processes are trying to do something with
shared data and the final outcome depends on the order in which the processes run.
Example: The program below outputs two strings: one from the child and one from
the parent. The program contains a race condition because the output depends on the
order in which the processes are run by the kernel and for how long each process runs.

#include "apue.h"
static void charatatime(char *);
int main(void)
{
pid_tpid;
if ((pid = fork()) < 0) { err_sys("fork error");
}
else if (pid == 0) {
charatatime("output from child\n");
} else {
charatatime("output from parent\n");
}
exit(0);
}
static void
charatatime(char *str)
{
char *ptr; int c;
setbuf(stdout, NULL);
for (ptr = str; (c = *ptr++) != 0; ) putc(c, stdout);
}

Output: $ ./a.out
ooutput from child
utput from parent
$ ./a.ou
t ooutput from child
utput from parent
$ ./a.out
output from child
output from parent

Dept of CSE, SIT, KLB. Page 19


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Q.08. a). What are pipes? What are its limitations? Write a program to send data from
parent to child over a pipe.
Ans:
Pipes:
Pipes are the oldest form of UNIX System IPC and are provided by all UNIX systems.
Pipes have two limitations.
1. Historically, they have been half duplex (i.e., data flows in only one direction). Some
systems now provide full-duplex pipes, but for maximum portability, we should never
assume that this is the case.
2. Pipes can be used only between processes that have a common ancestor. Normally,apipe is
created by a process, that process calls fork, and the pipe is used between the parent and the
child.
Send data from parent to child over a pipe:
#include "apue.h"
int main(void)
{
int n;
int fd[2];
pid_tpid;
char line[MAXLINE];
if (pipe(fd) < 0 )
err_sys("pipe error");
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid> 0) {
close(fd[0]);
write(fd[1], "hello world\n", 12);
} else {
close(fd[1]); n=read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);

Dept of CSE, SIT, KLB. Page 20


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

}
exit(0); }

b) What is a FIFO? With a neat diagram explain client server communication using
FIFO.
Ans:
FIFOs:
FIFOs are sometimes called named pipes. Unnamed pipes can be used only between related
processes when a common ancestor has created the pipe. With FIFOs, however, unrelated
processes can exchange data.
Client–Server Communication Using a FIFO:
 If we have a server that is contacted by numerous clients, each client can write its
request to a well-known FIFO that the server creates. Figure 15.22 shows this
arrangement.

 Since there are multiple writers for the FIFO, the requests sent by the clients to the
server need to be less than PIPE_BUF bytes in size. This prevents any interleaving of
the client writes.
 A single FIFO can’t be used, as the clients would never know when to read their
response versus responses for other clients.

Dept of CSE, SIT, KLB. Page 21


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

 One solution is for each client to send its process ID with the request. The server then
creates a unique FIFO for each client, using a pathname based on the client’s process
ID.
 For example, the server can create a FIFO with the name /tmp/serv1.XXXXX, where
XXXXX is replaced with the client’s process ID. This arrangement is shown in Figure
15.23.
 This arrangement works, although it is impossible for the server to tell whether a
client crashes. A client crash leaves the client-specific FIFO in the file system.
 The server also must catch SIGPIPE, since it’s possible for a client to send a request
and terminate before reading the response, leaving the client-specific FIFO with one
writer (the server) and no reader.

 With the arrangement shown in Figure 15.23, if the server opens its well-known FIFO
read-only (since it only reads from it) each time the number of clients goes from 1 to
0, the server will read an end of file on the FIFO. To prevent the server from having to
handle this case, a common trick is just to have the server open its well-known FIFO
for read–write.

Dept of CSE, SIT, KLB. Page 22


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

MODULE-5

Q9.a) Define Signal? Explain sigprocmask function with a program?


Ans: Signal:
Signals are software interrupts. Most nontrivial application programs need to deal with
signals. Signals provide a way of handling asynchronous events.
 sigprocmask Function
 The signal mask of a process is the set of signals currently blocked from delivery to
that process.
 A process can examine its signal mask, change its signal mask, or perform both
operations in one step by calling the following function.
#include<signal.h>
int sigprocmask(int how, constsigset_t *restrict set, sigset_t *restrict oset);
Returns: 0 if OK, −1 on error
 First, if oset is a non-null pointer, the current signal mask for the process is returned
through oset.
 Second, if set is a non-null pointer, the how argument indicates how the current signal
mask is modified.
 After calling sigprocmask, if any unblocked signals are pending, at least one of these
signals is delivered to the process before sigprocmask returns.
 The sigprocmask function is defined only for single-threaded processes. A separate
function is provided to manipulate a thread’s signal mask in a multithreaded process.
Example shows a function that prints the names of the signals in the signal mask of the
calling process.
#include "apue.h"
#include<errno.h>
void pr_mask(const char *str)
{
sigset_tsigset;
int errno_save;
errno_save = errno;
if (sigprocmask(0, NULL, &sigset) < 0) {
err_ret("sigprocmask error");
} else {

Dept of CSE, SIT, KLB. Page 23


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

printf("%s", str);
if (sigismember(&sigset, SIGINT))
printf(" SIGINT");
if (sigismember(&sigset, SIGQUIT))
printf(" SIGQUIT");
if (sigismember(&sigset, SIGUSR1))
printf(" SIGUSR1");
if (sigismember(&sigset, SIGALRM))
printf(" SIGALRM");
printf("\n");
}
errno = errno_save;
}
b. Explain Daemon characteristics and coding rules.
Ans:Daemon Characteristics:
The characteristics of daemons are:
1. Runs in the Background: Daemons operate independently of the controlling
terminal and are not interactive. They run in the background, often starting during
system boot and continuing until the system shuts down.
2. Detached from a Controlling Terminal: A daemon is typically disassociated
from the terminal that started it. This is done to avoid interference with user sessions
and ensure that the daemon continues running even if the user logs out.
3. Parent Process is init :When a daemon is created, it typically forks a child
process. The parent process exits, and the child process is reparented to the init
process (PID 1). This ensures the daemon is independent and adopts a clean
environment.
4. Independent of User Sessions:Daemons are designed to operate without being tied
to a specific user session. This allows them to serve all users or manage system
resources universally.
5. No User Interface:Daemons do not have a graphical user interface (GUI) or
command-line interface (CLI). They communicate through files, sockets, or system
logs.
6. File System Context: Many daemons use the root directory (/) as their working
directory to ensure they do not keep other file systems mounted unnecessarily.
Dept of CSE, SIT, KLB. Page 24
UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

7. Log Output: Daemons log their activities and errors to system log files, typically
using facilities like syslog.
8. Use of a Unique PID File: Daemons often write their process ID (PID) to a
specific file in /var/run/ or a similar directory. This helps other processes or
administrators identify the daemon and manage it (e.g., restarting or stopping).
9. Signal Handling: Daemons handle Unix signals for operations like reload
(SIGHUP), stop (SIGTERM), or other custom commands.

CODING RULES:
Call umask to set the file mode creation mask to 0. The file mode creation mask that's
inherited could be set to deny certain permissions. If the daemon process is going to create
files, it may want to set specific permissions.

Call fork and have the parent exit. This does several things. First, if the daemon was
started as a simple shell command, having the parent terminate makes the shell think that the
command is done. Second, the child inherits the process group ID of the parent but gets a
new process ID, so we're guaranteed that the child is not a process group leader.
Call setsid to create a new session. The process (a) becomes a session leader of a new
session, (b) becomes the process group leader of a new process group, and (c) has no
controlling terminal.

Change the current working directory to the root directory. The current working
directory inherited from the parent could be on a mounted file system. Since daemons
normally exist until the system is rebooted, if the daemon stays on a mounted file system, that
file system cannot be unmounted.
Unneeded file descriptors should be closed. This prevents the daemon from holding open
any descriptors that it may have inherited from its parent.

Some daemons open file descriptors 0, 1, and 2 to /dev/null so that any library
routines that try to read from standard input or write to standard output or standard
error will have no effect. Since the daemon is not associated with a terminal device, there is
nowhere for output to be displayed; nor is there anywhere to receive input from an interactive
user.

Dept of CSE, SIT, KLB. Page 25


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

Q10.a. )What is a daemon process? Explain coding rules and error logging.
Ans:Daemon process:
Daemons are processes that live for a long time. They are often started when the system is
bootstrapped and terminate only when the system is shut down.
They don’t have a controlling terminal, we say that they run in the background. UNIX
systems have numerous daemons that perform day-to-day activities.
CODING RULES :
Call umask to set the file mode creation mask to 0. The file mode creation mask that's
inherited could be set to deny certain permissions. If the daemon process is going to create
files, it may want to set specific permissions.

Call fork and have the parent exit. This does several things. First, if the daemon was
started as a simple shell command, having the parent terminate makes the shell think that the
command is done. Second, the child inherits the process group ID of the parent but gets a
new process ID, so we're guaranteed that the child is not a process group leader.
Call sets id to create a new session. The process (a) becomes a session leader of a new
session, (b) becomes the process group leader of a new process group, and (c) has no
controlling terminal.
Change the current working directory to the root directory. The current working
directory inherited from the parent could be on a mounted file system. Since daemons
normally exist until the system is rebooted, if the daemon stays on a mounted file system, that
file system cannot be unmounted.
Unneeded file descriptors should be closed. This prevents the daemon from holding open
any descriptors that it may have inherited from its parent.
Some daemons open file descriptors 0, 1, and 2 to /dev/null so that any library
routines that try to read from standard input or write to standard output or standard
error will have no effect. Since the daemon is not associated with a terminal device, there is
nowhere for output to be displayed; nor is there anywhere to receive input from an interactive
user.
ERROR LOGGING:
One problem a daemon has is how to handle error messages. It can't simply write to standard
error, since it shouldn't have a controlling terminal. We don't want all the daemons writing to
the console device, since on many workstations, the console device runs a windowing system.
A central daemon error-logging facility is required.

Dept of CSE, SIT, KLB. Page 26


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

There are three ways to generate log messages:

 Kernel routines can call the log function. These messages can be read by any user process
that opens and reads the /dev/klog device.

 Most user processes (daemons) call the syslog(3) function to generate log messages. This
causes the message to be sent to the UNIX domain datagram socket /dev/log.

 A user process on this host, or on some other host that is connected to this host by a
TCP/IP network, can send log messages to UDP port 514. Note that the syslog function
never generates these UDP datagrams: they require explicit network programming by the
process generating the log message.

b. Explain the following functions: i)system() ii) sleep() .


Ans:
i) system() :
 POSIX.1 requires that system ignore SIGINT and SIGQUIT and block SIGCHLD.
Before showing a version that handles these signals correctly, let’s see why we need
to worry about signal handling.

 When the editor terminates, the system sends the SIGCHLD signal to the parent
 We catch it and return from the signal handler. But if it is catching the SIGCHLD
signal, the parent should be doing so because it has created its own children, so that it
knows when its children have terminated.
 The delivery of this signal in the parent should be blocked while the system function
is executing. Indeed, this is what POSIX.1 specifies.
 Otherwise, when the child created by system terminates, it would fool the caller of
system into thinking that one of its own children terminated.
Dept of CSE, SIT, KLB. Page 27
UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

#include "apue.h"
static void
sig_int(int signo)
{
printf("caught SIGINT\n");
}
static void
sig_chld(int signo)
{
printf("caught SIGCHLD\n");
}
int main(void)
{
if (signal(SIGINT, sig_int) == SIG_ERR)
err_sys("signal(SIGINT) error");
if (signal(SIGCHLD, sig_chld) == SIG_ERR)
err_sys("signal(SIGCHLD) error");
if (system("/bin/ed") < 0)
err_sys("system() error");
exit(0);
}

ii) sleep():
 We’ve used the sleep function in numerous examples throughout the text, and we
showed two flawed implementations of it.
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
Returns: 0 or number of unslept seconds.
 This function causes the calling process to be suspended until either 1. The amount of
wall clock time specified by seconds has elapsed. 2. A signal is caught by the process
and the signal handler returns.

Dept of CSE, SIT, KLB. Page 28


UNIX SYSTEM PROGRAMMING (BCS515C)
SOLVED MODEL QUESTION PAPER (2022 SCHEME)

 As with an alarm signal, the actual return may occur at a time later than requested
because of other system activity.
 In case 1, the return value is 0. When sleep returns early because of some signal being
caught (case 2), the return value is the number of unslept seconds (the requested time
minus the actual time slept).

#include<signal.h>
#include<stdio.h>
#include<unistd.h>
void wakeup( )
{;}
unsigned int sleep (unsigned int timer )
{
struct sigaction action;
action.sa_handler=wakeup;
action.sa_flags=0;
sigemptyset(&action.sa_mask);
if(sigaction(SIGALARM,&action,0)==-1)
{
perror(“sigaction”);
return -1;
}
(void) alarm (timer);
(void) pause( );
return 0;
}

Dept of CSE, SIT, KLB. Page 29

You might also like