OS Lab Manual PDF
OS Lab Manual PDF
LAB MANUAL
PREPARED BY
DR. NAVEEN CHAUDHARY
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
DISCLAIMER
The e-Manual on “OPERATING SYSTEMS”is
prepared as per the syllabus offered to students of
Computer Science & Engineering, CTAE, MPUAT,
Udaipur, enrolled for undergraduate (B. Tech) degree
programme.
This document is a compilation of materials
provided in text books, and e-contents freely available
on online sources. The author does not claim for
originality of work. This is meant purely for academic
purpose for students of Computer Science and
Engineering, CTAE, MPUAT as a reference Material
for understanding of course. Multiplication and use of
this e-manual for commercial activity is strictly
prohibited.
However, author shall in no event be liable for
any errors, omissions or damages arising out of use this
information and specially disclaim any warranties or
merchantability or fitness for any particular use.
fghfh
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
CONTENTS
Sno Name of Experiment
Write a program to display a file page wise assuming a page has 10 lines
1.
and each line has 80 characters
Write a Program which converts all the small case letters in a file into
2.
appropriate capital letters.
3. Write a program to print the details of the system (use uname sys call)
Write a program which will print the list of environment variable and also
4.
print the value of the PATH system variable
Write a program to print current (soft) limit and maximum (Hard) limits
5.
of all resources
6. Write a program with an exit handler that outputs CPU usage.
7. Write a program that prints it’s & it’s parent’s process ID.
8. Write a program that prints out various user & group ID’s.
Write a program which uses fork to create a child process& then parent &
9.
child print their respective process ID’s
Write a program that creates a chain of n processes, where n is a
10.
command line argument.
Write a program that creates a fan of n processes where n is passed as a
11.
command line argument.
Write a program to show that same opened file can be shared by both
12.
parent and child processes
13. Write a program that creates a child process to run ls – l
Write a program to create a zombie child and find its status using system
14.
(ps) command
15. Write a program to copy a file.
Write a program for which output is automatically directed to a named
16.
file rather than on to the console
Write a program that redirects standards output to the file my.file (or
17. Write a program that do the following operation cat XYZ > myfile). using
dup2 rather than dup
18. Write a program to create an empty directory using system calls
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -1
Aim -Write a program to display a file page wise assuming a page has 10 lines and each line
has 80 characters
Code –
#include<stdio.h>
#include<stdlib.h>
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg1 pg1.cpp
CTAE@CTAE-VB:~/osLab$ ./pg1 pg1input
An operating system (OS) is system software that manages computer
hardware and software resources and provides common services for
computer programs.
Name
fprintf - formatted output conversion
Synopsis
#include <stdio.h>
int fprintf(FILE *stream, const char *format, ...);
Description
fprintf() write output to the given output stream;
Return value
Upon successful return, these functions return the number of characters printed (excluding the
null byte used to end output to strings).
---------------------------
Name
fopen - stream open functions
Synopsis
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
Description
The fopen() function opens the file whose name is the string pointed to by path and associates
a stream with it. The argument mode points to a string beginning with one of the following
sequences (possibly followed by additional characters, as described below):
r - Open text file for reading. The stream is positioned at the beginning of the file.
r+ - Open for reading and writing. The stream is positioned at the beginning of the file.
W - Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
w+ - Open for reading and writing. The file is created if it does not exist, otherwise it is
truncated. The stream is positioned at the beginning of the file.
a - Open for appending (writing at end of file). The file is created if it does not exist. The
stream is positioned at the end of the file.
a+ - Open for reading and appending (writing at end of file). The file is created if it does not
exist. The initial file position for reading is at the beginning of the file, but output is always
appended to the end of the file.
Return Value
Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer.
Otherwise, NULL is returned and errno is set to indicate the error.
-------------------------
Name
feof - check and reset stream status
Synopsis
#include <stdio.h>
int feof(FILE *stream);
Description
The function feof() tests the end-of-file indicator for the stream pointed to by stream,
returning nonzero if it is set.
-------------------------
Name
fgets - input of characters and strings
Synopsis
#include <stdio.h>
char *gets(char *s);
Description
fgets() reads in at most one less than size characters from stream and stores them into
the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is
read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last
character in the buffer.
Return Value
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
gets() return s on success, and NULL on error or when end of file occurs while no characters
have been read.
-------------------------
Name
fclose - close a stream
Synopsis
#include <stdio.h>
int fclose(FILE *stream);
Description
The fclose() function flushes the stream pointed to by stream (writing any buffered
output data using fflush(3)) and closes the underlying file descriptor.
Return value
Upon successful completion, 0 is returned. Otherwise, EOF is returned and errno
is set to indicate the error.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -2
Aim -Write a Program which converts all the small case letters in a file into appropriate
capital letters.
Code –
#include<stdio.h>
#include<stdlib.h>
main(int argc, char *argv[])
{
FILE *fp, *ft;
char ch;
if(argc!=2)
{
fprintf(stderr,"Usage: ./a.out file name\n");
exit(1);
}
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("can't open file");
exit(1);
}
ft=fopen("temp","w");
while(!feof(fp))
{
ch=fgetc(fp);
if(ch>=97&&ch<=122)
ch=ch+'A' - 'a';
fputc(ch,ft);
}
fclose(ft);
fclose(fp);
ft=fopen("temp","r");
fp=fopen(argv[1],"w");
if(ft!=NULL)
{
while(!feof(ft))
{
ch=fgetc(ft);
fputc(ch,fp);
}
fclose(ft);
fclose(fp);
}
else
printf("Error in opening file");
}
Output: -
CTAE@CTAE-VB:~/osLab$ cat pg2input
convert in capital
CTAE@CTAE-VB:~/osLab$ ./pg2 pg2input
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
fgetc - input of characters and strings
Synopsis
#include <stdio.h>
int fgetc(FILE *stream);
Description
fgetc() reads the next character from stream and returns it as an unsigned char cast to
an int, or EOF on end of file or error.
Return Value
fgetc()return the character read as an unsigned char cast to an int or EOF on end of
file or error
--------------------------
Name
fputc - output of characters and strings
Synopsis
#include <stdio.h>
int fputc(int c, FILE *stream);
Description
fputc() writes the character c, cast to an unsigned char, to stream
Return Value
fputc() return the character written as an unsigned char cast to an int or EOF on error.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -3
Aim - Write a program to print the details of the system (use uname sys call)
Code –
// compare your result with uname command
// do man 2 uname(2) to understand the uname() function and
structure utsname
#include<stdio.h>
#include<sys/utsname.h>
main()
{
struct utsname u;
if(uname(&u)!=0)
fprintf(stderr, "Uname Error");
printf("\n%s \n %s \n %s \n %s \n
%s\n",u.sysname,u.nodename,u.release,u.version,u.machine);
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg3 pg3.cpp
CTAE@CTAE-VB:~/osLab$ ./pg3
Linux
CTAE-VB
4.15.0-45-generic
#48~16.04.1-Ubuntu SMP Tue Jan 29 18:03:19 UTC 2019
i686
CTAE@CTAE-VB:~/osLab$uname -a
Linux CTAE-VB 4.15.0-45-generic #48~16.04.1-Ubuntu SMP Tue Jan 29
18:03:19 UTC 2019 i686i686i686 GNU/Linux
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
uname - get name and information about current kernel
Synopsis
#include <sys/utsname.h>
int uname(struct utsname *buf);
Description
uname() returns system information in the structure pointed to bybuf. The utsname struct is
defined in <sys/utsname.h>:
struct utsname {
char sysname[]; /* Operating system name (e.g., "Linux") */
char nodename[]; /* Name within "some implementation-defined
network" */
char release[]; /* Operating system release (e.g., "2.6.28") */
char version[]; /* Operating system version */
char machine[]; /* Hardware identifier */
#ifdef _GNU_SOURCE
char domainname[]; /* NIS or YP domain name */
#endif
};
The length of the arrays in a struct utsname is unspecified; the fields are terminated by a null
byte ('\0').
Return value
On success, zero is returned. On error, -1 is returned, and errno isset appropriately.
-------------------------
Name
uname - print system information
Synopsis
uname [OPTION]...
Description
Print certain system information. With no OPTION, same as -s.
-a, --all
print all information, in the following order, except omit -p
and -i if unknown:
-s, --kernel-name
print the kernel name
-n, --nodename
print the network node hostname
-r, --kernel-release
print the kernel release
-v, --kernel-version
print the kernel version
-m, --machine
print the machine hardware name
-p, --processor
print the processor type or "unknown"
-i, --hardware-platform
print the hardware platform or "unknown"
-o, --operating-system
print the operating system
--help display this help and exit
--version
output version information and exit
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -4
Aim - Write a program which will print the list of environment variable and also print the
value of the PATH system variable
Code –
//To print all environment variables
#include<stdio.h>
#include<stdlib.h>
extern char **environ;
//the external variable environ points to the process
//environment list when the process begins executing.
//do man environ
int main(void)
{
int i;
char *path;
printf("The environment list follows: \n");
for(i=0;environ[i] != NULL; i++)
printf("environ[%d]: %s\n", i, environ[i]);
if ((path =getenv("PATH")) == NULL)// do man getenv
printf("PATH environment variable not set\n");
else
printf("The value of PATH variable = %s\n", path);
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg4 pg4.cpp
CTAE@CTAE-VB:~/osLab$ ./pg4
w=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;
31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzm
a=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:
*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.l
zo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:
*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;
31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpi
o=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*
.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;
35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.sv
g=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35
:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4
=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*
.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;
35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=0
1;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.a
ac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;3
6:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=0
0;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
environ[15]: QT_ACCESSIBILITY=1
environ[16]:
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
environ[17]: XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
environ[18]: SSH_AUTH_SOCK=/run/user/1000/keyring/ssh
environ[19]: DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path
environ[20]: XDG_CONFIG_DIRS=/etc/xdg/xdg-
ubuntu:/usr/share/upstart/xdg:/etc/xdg
environ[21]:
PATH=/home/CTAE/bin:/home/CTAE/.local/bin:/usr/local/sbin:/usr/local
/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap
/bin
environ[22]: DESKTOP_SESSION=ubuntu
environ[23]: QT_IM_MODULE=ibus
environ[24]: QT_QPA_PLATFORMTHEME=appmenu-qt5
environ[25]: XDG_SESSION_TYPE=x11
environ[26]: PWD=/home/CTAE/osLab
environ[27]: JOB=gnome-session
environ[28]: XMODIFIERS=@im=ibus
environ[29]: GNOME_KEYRING_PID=
environ[30]: LANG=en_IN
environ[31]: GDM_LANG=en_US
environ[32]: MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path
environ[33]: IM_CONFIG_PHASE=1
environ[34]: COMPIZ_CONFIG_PROFILE=ubuntu
environ[35]: GDMSESSION=ubuntu
environ[36]: SESSIONTYPE=gnome-session
environ[37]: GTK2_MODULES=overlay-scrollbar
environ[38]: HOME=/home/CTAE
environ[39]: XDG_SEAT=seat0
environ[40]: SHLVL=1
environ[41]: LANGUAGE=en_IN:en
environ[42]: LIBGL_ALWAYS_SOFTWARE=1
environ[43]: GNOME_DESKTOP_SESSION_ID=this-is-deprecated
environ[44]: UPSTART_INSTANCE=
environ[45]: UPSTART_EVENTS=started starting
environ[46]: XDG_SESSION_DESKTOP=ubuntu
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
environ[47]: LOGNAME=CTAE
environ[48]: QT4_IM_MODULE=xim
environ[49]:
XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/u
sr/share:/var/lib/snapd/desktop
environ[50]: DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-
VVGiZpOatm
environ[51]: LESSOPEN=| /usr/bin/lesspipe %s
environ[52]: INSTANCE=Unity
environ[53]: UPSTART_JOB=unity-settings-daemon
environ[54]: XDG_RUNTIME_DIR=/run/user/1000
environ[55]: DISPLAY=:0
environ[56]: XDG_CURRENT_DESKTOP=Unity
environ[57]: GTK_IM_MODULE=ibus
environ[58]: LESSCLOSE=/usr/bin/lesspipe %s %s
environ[59]: XAUTHORITY=/home/CTAE/.Xauthority
environ[60]: _=./pg4
environ[61]: OLDPWD=/home/CTAE
The value of PATH variable =
/home/CTAE/bin:/home/CTAE/.local/bin:/usr/local/sbin:/usr/local/bin:
/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
environ - user environment
Synopsis
extern char **environ;
Description
The variable environ points to an array of pointers to strings calledthe "environment". The last
pointer in this array has the value NULL.(This variable must be declared in the user program, but is
declared inthe header file <unistd.h> if the _GNU_SOURCE feature test macro isdefined.) This
array of strings is made available to the process bythe exec(3) call that started the process.
By convention the strings in environ have the form "name=value". Common examples are:
USER
The name of the logged-in user (used by some BSD-derived programs).
LOGNAME
The name of the logged-in user (used by some System-V derive programs).
HOME
A user's login directory, set by login(1) from the password filepasswd(5).
LANG
The name of a locale to use for locale categories when not overridden by LC_ALL or more
specific environment variables such as LC_COLLATE, LC_CTYPE, LC_MESSAGES,
LC_MONETARY, LC_NUMERIC, andLC_TIME (see locale(7) for further details of the
LC_* environment variables).
PATH
The sequence of directory prefixes that sh(1) and many other programs apply in searching
for a file known by an incomplete pathname. The prefixes are separated by ‘:’ (Similarly
one has CDPATH used by some shells to find the target of a changedirectory command,
MANPATH used by man(1) to find manual pages,and so on)
PWD
The current working directory. Set by some shells.
SHELL
The pathname of the user's login shell.
TERM
The terminal type for which output is to be prepared.
PAGER
The user's preferred utility to display text files.
EDITOR/VISUAL
The user's preferred utility to edit text files.
--------------------------------
Name
getenv - get an environment variable
Synopsis
#include <stdlib.h>
char *getenv(const char *name);
Description
The getenv() function searches the environment list to find the environment variable name,
and returns a pointer to the corresponding value string.
Return Value
The getenv() function returns a pointer to the value in the environment, or NULL if there is
no match.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -5
Aim -Write a program to print current (soft) limit and maximum (Hard) limits of all
resources
// To print current and max limits of all resources // pg 180 WR stevens
// do man getrlimit for more details
// -1 may mean no limit set for the resource ie the limit is infinity
Code –
#include<stdio.h>
#include<stdlib.h>
main()
{
struct rlimit rl;
int i;
printf("\n Resources Name \t Current Limit \tMax Limit \t");
for(i=0;i<=10;i++)
{
if(getrlimit(i, &rl)<0)
{
printf("Error in grelimit\n");
exit(1);
}
switch(i)
{
case RLIMIT_CPU :
printf("\nRLIMIT_CPU\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_DATA:
printf("\nRLIMIT_DATA\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_FSIZE:
printf("\nRLIMIT_FSIZE\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_MEMLOCK:
printf("\nRLIMIT_MEMLOCK\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_NOFILE:
printf("\nRLIMIT_NOFILE\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_NPROC:
printf("\nRLIMIT_NPROC\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
/*case RLIMIT_OFILE:
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
printf(Â"\nRLIMIT_OFILE\t%d\t\t%dÂ",rl.rlim_cur,rl.rlim_max)
;
break;*/
case RLIMIT_RSS:
printf("\nRLIMIT_RSS\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_STACK:
printf("\nRLIMIT_STACK\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
case RLIMIT_LOCKS:
printf("\nRLIMIT_LOCKS\t%d\t\t%d",rl.rlim_cur,rl.rlim_max);
break;
}
}
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg5 pg5.cpp
CTAE@CTAE-VB:~/osLab$ ./pg5
Name
getrlimit, setrlimit, prlimit - get/set resource limits
Synopsis
#include <sys/time.h>
#include <sys/resource.h>
Description
The getrlimit() and setrlimit() system calls get and set resource limits. Each resource has an
associated soft and hard limit, as defined by the rlimit structure:
struct rlimit {
rlim_t rlim_cur; /* Soft limit */
rlim_t rlim_max; /* Hard limit (ceiling for rlim_cur) */
};
The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts
as a ceiling for the soft limit: an unprivileged process may set only its soft limit to a value in the
range from 0 up to the hard limit, and (irreversibly) lower its hard limit. A privileged process (under
Linux: one with the CAP_SYS_RESOURCE capability) may make arbitrary changes to either limit
value.
RLIMIT_CPU
CPU time limit in seconds. When the process reaches the soft limit, it is sent a SIGXCPU
signal. The default action for this signal is to terminate the process. However, the signal
can be caught, and the handler can return control to the main program. If the process
continues to consume CPU time, it will be sent SIGXCPU once per second until the hard
limit is reached, at which time it is sent SIGKILL.
RLIMIT_FSIZE
The maximum size of files that the process may create.
RLIMIT_DATA
The maximum size of the process's data segment (initialized data, uninitialized data, and
heap).
RLIMIT_STACK
The maximum size of the process stack, in bytes.
RLIMIT_RSS
Specifies the limit (in bytes) of the process's resident set (the number of virtual pages resident
in RAM).
RLIMIT_NPROC
The maximum number of processes (or, more precisely on Linux, threads) that can be created
for the real user ID of the calling process.
RLIMIT_NOFILE
Specifies a value one greater than the maximum file descriptor number that can be
opened by this process.
RLIMIT_MEMLOCK
The maximum number of bytes of memory that may be locked into RAM.
RLIMIT_LOCKS (Early Linux 2.4 only)
A limit on the combined number of flock(2) locks and fcntl(2) leases that this process may
establish.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -6
Aim -Write a program with an exit handler that outputs CPU usage.
Code –
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/times.h>
#include <time.h> //modified
static void showtimes(void)
{
time_t time1, time2;
time_t time_dif;
time1 = time(NULL); //man time,
//time(NULL) returns current time in seconds
printf("time1 : %ld",time1);
sleep(5); // man sleep
time2 = time(NULL);
printf("\ntime2 : %ld",time2);
time_dif = difftime(time2,time1); // man difftime
printf("\nthe showtime slept for: %ld seconds\n",time_dif);
}
int main(void)
{
if (atexit(showtimes)) // man atexit
{
fprintf(stderr, "Failed to install showtimes exit
handler\n");
return 1;
}
/* rest of main program goes here */
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg6 pg6.cpp
CTAE@CTAE-VB:~/osLab$ ./pg6
time1 : 1555142636
time2 : 1555142641
the showtime slept for: 5 seconds
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
time - get time in seconds
Synopsis
#include <time.h>
time_t time(time_t *t);
Description
time() returns the time as the number of seconds since the Epoch, 1970-01-01
00:00:00 +0000 (UTC).If t is non-NULL, the return value is also stored in the
memory pointed to by t.
Return Value
On success, the value of time in seconds since the Epoch is returned. On error,
((time_t) -1) is returned, and errno is set appropriately.
-------------------------
Name
sleep - sleep for a specified number of seconds
Synopsis
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
Description
sleep() causes the calling thread to sleep either until the number ofreal-time seconds
specified in seconds have elapsed or until a signalarrives which is not ignored.
Return value
Zero if the requested time has elapsed, or the number of seconds leftto sleep, if the call
was interrupted by a signal handler.
--------------------------
Name
difftime - calculate time difference
Synopsis
#include <time.h>
double difftime(time_t time1, time_t time0);
Description
The difftime() function returns the number of seconds elapsed between time time1 and
time time0, represented as a double. Each ofthe times is specified in calendar time,
which means its value is a measurement (in seconds) relative to the Epoch, 1970-01-
0100:00:00 +0000 (UTC).
---------------------------
Name
atexit - register a function to be called at normal process termination
Synopsis
#include <stdlib.h>
int atexit(void (*function)(void));
Description
The atexit() function registers the given function to be called atnormal process
termination, either via exit(3) or via return from theprogram's main().
Return value
The atexit() function returns the value 0 if successful; otherwise itreturns a nonzero
value.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -7
Aim -Write a program that prints it’s & it’s parent’s process ID.
Code –
#include<stdio.h>
#include <unistd.h>
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg7 pg7.cpp
CTAE@CTAE-VB:~/osLab$ ./pg7
I am process 14003
My parent is 13560
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
getpid, getppid - get process identification
Synopsis
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void);
pid_t getppid(void);
Description
getpid() returns the process ID of the calling process.
getppid() returns the process ID of the parent of the calling process.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -8
Aim -Write a program that prints out various user & group ID’s.
Code –
#include <stdio.h>
#include <unistd.h>
int main(void)
{ // man getuid, man getgid
printf("My real user ID is %5ld\n", (long)getuid());
printf("My effective user ID is %5ld\n", (long)geteuid());
printf("My real group ID is %5ld\n", (long)getgid());
printf("My effective group ID is %5ld\n", (long)getegid());
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg8 pg8.cpp
CTAE@CTAE-VB:~/osLab$ ./pg8
My real user ID is 1000
My effective user ID is 1000
My real group ID is 1000
My effective group ID is 1000
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
NAME
getuid, geteuid - get user identity
SYNOPSIS
#include <unistd.h>
#include <sys/types.h>
uid_t getuid(void);
uid_t geteuid(void);
DESCRIPTION
getuid() returns the real user ID of the calling process.
geteuid() returns the effective user ID of the calling process.
------------------------------
NAME
getgid, getegid - get group identity
SYNOPSIS
#include <unistd.h>
#include <sys/types.h>
gid_t getgid(void);
gid_t getegid(void);
DESCRIPTION
getgid() returns the real group ID of the calling process.
getegid() returns the effective group ID of the calling process.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -9
Aim -Write a program which uses fork to create a child process& then parent & child print
their respective process ID’s
Code –
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
pid_t childpid;
childpid = fork();
if (childpid == -1)
{
perror("Failed to fork");
return 1;
}
if (childpid == 0) /* child code */
printf("I am child %ld\n", (long)getpid());
else /* parent code */
printf("I am parent %ld\n", (long)getpid());
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ ./pg9
I am parent 14054
CTAE@CTAE-VB:~/osLab$ I am child 14055
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
NAME
fork - create a child process
SYNOPSIS
#include <unistd.h>
pid_t fork(void);
DESCRIPTION
fork() creates a new process by duplicating the calling process. The new process is referred to as
the child process. The calling process is referred to as the parent process.
The child process and the parent process run in separate memory spaces. At the time of fork()
both memory spaces have the same content. Memory writes, file mappings (mmap(2)), and
unmappings (munmap(2)) performed by one of the processes do not affect the other.
RETURN VALUE
On success, the PID of the child process is returned in the parent, and 0 is returned in the child.
On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -10
Aim -Write a program that creates a chain of n processes, where n is a command line
argument.
Code –
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg10 pg10.cpp
CTAE@CTAE-VB:~/osLab$ ./pg10 5
i:1 process ID:14125 parent ID:13560 child ID:14126
CTAE@CTAE-VB:~/osLab$ i:2 process ID:14126 parent ID:1220 child
ID:14127
i:3 process ID:14127 parent ID:1220 child ID:14128
i:4 process ID:14128 parent ID:1220 child ID:14129
i:5 process ID:14129 parent ID:1220 child ID:0
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -11
Aim -Write a program that creates a fan of n processes where n is passed as a command line
argument.
Code –
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg11 pg11.cpp
CTAE@CTAE-VB:~/osLab$ ./pg11 5
i:5 process ID:14157 parent ID:13560 child ID:14161
CTAE@CTAE-VB:~/osLab$ i:4 process ID:14161 parent ID:1220 child
ID:0
i:3 process ID:14160 parent ID:1220 child ID:0
i:2 process ID:14159 parent ID:1220 child ID:0
i:1 process ID:14158 parent ID:1220 child ID:0
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
atoi - convert a string to an integer
Synopsis
#include <stdlib.h>
int atoi(const char *nptr);
Description
The atoi() function converts the initial portion of the string pointed to by nptr to int.
Return Value
The converted value.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -12
Aim -Write a program to show that same opened file can be shared by both parent and child
processes
Code –
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
FILE *fp;
int fd;
char ch;
fp=fopen("test","w");
fprintf(fp,"%s\n","This line is written by PARRENT PROCESS");
fflush(NULL);
fd=fork();
if(fd < 0)
{
printf("Fork Error");
exit(1);
}
if(fd == 0)
{
fprintf(fp,"%s","This line is written by CHILD PROCESS\n");
fclose(fp);
fp=fopen("test","r");
while(!feof(fp))
printf("%c",getc(fp));
}
if(fd > 0)
{ // man 2 wait
if (fd != wait(NULL)) /* parent code */
{
perror("Parent failed to wait due to signal or error");
return 1;
}
}
fclose(fp);
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg12 pg12.cpp
CTAE@CTAE-VB:~/osLab$ ./pg12
This line is written by PARRENT PROCESS
This line is written by CHILD PROCESS
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
fflush - flush a stream
Synopsis
#include <stdio.h>
int fflush(FILE *stream);
Description
For output streams, fflush() forces a write of all user-space buffered data for the given
output or update stream via the stream's underlying write function.
For input streams, fflush() discards any buffered data that has been fetched from the
underlying file, but has not been consumed by the application. The open status of the
stream is unaffected.
If the stream argument is NULL, fflush() flushes all open output streams.
Return Value
Upon successful completion 0 is returned. Otherwise, EOF is returned and errno is set
to indicate the error.
----------------------------
Name
wait - wait for process to change state
Synopsis
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
Description
The wait() system call suspends execution of the calling process until one of its
children terminates.
-----------------------------
Name
perror - print a system error message
Synopsis
#include <stdio.h>
void perror(const char *s);
Description
The perror() function produces a message on standard error describingthe last error
encountered during a call to a system or libraryfunction.
First (if s is not NULL and *s is not a null byte ('\0')), theargument string s is printed,
followed by a colon and a blank
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -13
Aim -Write a program that creates a child process to run ls – l
Code –
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t childpid;
childpid = fork();
if (childpid == -1)
{
perror("Failed to fork");
return 1;
}
if (childpid == 0)
{ /* child code */
execl("/bin/ls", "ls", "-l", NULL); // man 2 exec
perror("Child failed to exec ls");
return 1;
}
if (childpid != wait(NULL)) /* parent code */
{
perror("Parent failed to wait due to signal or error");
return 1;
}
return 0;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg13 pg13.cpp
CTAE@CTAE-VB:~/osLab$ ./pg13
total 144
-rwxrwxr-x 1 CTAECTAE 7536 Apr 13 13:43 a.out
-rwxrwxr-x 1 CTAECTAE 7536 Apr 13 13:45 pg10
-rw-rw-r-- 1 CTAECTAE 565 Apr 13 13:41 pg10.cpp
-rwxrwxr-x 1 CTAECTAE 7536 Apr 13 13:46 pg11
-rw-rw-r-- 1 CTAECTAE 560 Apr 13 13:46 pg11.cpp
-rwxrwxr-x 1 CTAECTAE 7784 Apr 13 13:50 pg12
-rw-rw-r-- 1 CTAECTAE 761 Apr 13 13:50 pg12.cpp
-rwxrwxr-x 1 CTAECTAE 7460 Apr 13 13:51 pg13
-rw-rw-r-- 1 CTAECTAE 594 Apr 13 13:51 pg13.cpp
-rwxrwxr-x 1 CTAECTAE 7508 Apr 13 13:20 pg3
-rw-rw-r-- 1 CTAECTAE 208 Apr 13 13:21 pg3.cpp
-rwxrwxr-x 1 CTAECTAE 7476 Apr 13 13:22 pg4
-rw-rw-r-- 1 CTAECTAE 566 Apr 13 13:22 pg4.cpp
-rwxrwxr-x 1 CTAECTAE 7512 Apr 13 13:28 pg5
-rw-rw-r-- 1 CTAECTAE 1417 Apr 13 13:29 pg5.cpp
-rwxrwxr-x 1 CTAECTAE 7620 Apr 13 13:35 pg6
-rw-rw-r-- 1 CTAECTAE 749 Apr 13 13:35 pg6.cpp
-rwxrwxr-x 1 CTAECTAE 7428 Apr 13 13:37 pg7
-rw-rw-r-- 1 CTAECTAE 185 Apr 13 13:37 pg7.cpp
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
execl- execute a file
Synopsis
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...
/* (char *) NULL */);
Description
The exec() family of functions replaces the current process image with a new process
image.
The initial argument for these functions is the name of a file that is to be executed.
The const char *arg and subsequent ellipses in the execl(), execlp(),and execle()
functions can be thought of as arg0, arg1, ..., argn.The list of arguments must be
terminated by a null pointer, and, since these are variadic functions, this pointer must be
cast (char *) NULL.
Return value
The exec() functions return only if an error has occurred. The returnvalue is -1, and
errno is set to indicate the error
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -14
Aim -Write a program to create a zombie child and find its status using system (ps) command
Code –
/*DEFUNCT MEANS ZOMBIE
Zombie process is a process that has terminated, but whose parent
has not yet waited for it. So parent's parent will become parent of
this process
Also remember if parent process dies before child process then init
process (process id = 1) becomes the parent of the executing child
process*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
main()
{
int fd;
if((fd=fork())<0)
{
printf("error in creating child");
exit(1);
}
if(fd==0)
kill(getpid(),SIGKILL);
else
sleep(2);
system("ps -f");
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg14 pg14.cpp
CTAE@CTAE-VB:~/osLab$ ./pg14
UID PID PPID C STIME TTY TIME CMD
CTAE 13560 13554 0 13:06 pts/4 00:00:00 bash
CTAE 14379 13560 0 14:19 pts/4 00:00:00 ./pg14
CTAE 14380 14379 0 14:19 pts/4 00:00:00 [pg14] <defunct>
CTAE 14381 14379 0 14:19 pts/4 00:00:00 sh -c ps -f
CTAE 14382 14381 0 14:19 pts/4 00:00:00 ps -f
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
exit - cause normal process termination
Synopsis
#include <stdlib.h>
void exit(int status);
Description
The exit() function causes normal process termination and the valueof status & 0377 is
returned to the parent
--------------------------
Name
ps - report a snapshot of the current processes.
Synopsis
ps [options]
Description
ps displays information about a selection of the active processes.
-f Do full-format listing.
---------------------------
Name
sleep - sleep for a specified number of seconds
Synopsis
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
Description
sleep() causes the calling thread to sleep either until the number ofreal-time seconds
specified in seconds have elapsed or until a signalarrives which is not ignored.
Return value
Zero if the requested time has elapsed, or the number of seconds leftto sleep, if the call
was interrupted by a signal handler.
----------------------------
Name
kill - send signal to a process
Synopsis
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
Description
The kill() system call can be used to send any signal to any process group or process.
If pid is positive, then signal sig is sent to the process with the ID specified by pid.
If pid equals 0, then sig is sent to every process in the process group of the calling
process.
If pid equals -1, then sig is sent to every process for which the calling process has
permission to send signals, except for process 1(init), but see below.
If pid is less than -1, then sig is sent to every process in the process group whose ID is
-pid.
If sig is 0, then no signal is sent, but existence and permission checks are still
performed; this can be used to check for the existence of a process ID or process
group ID that the caller is permitted to signal.
Return value
On success (at least one signal was sent), zero is returned. Onerror, -1 is returned, and
errno is set appropriately.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -15
Aim -Write a program to copy a file.
Code –
// the copyfile.c function copies a file fromfd to tofd
#include <errno.h>
#include <unistd.h>
#define BLKSIZE 1024
for ( ; ; )
{
while (((bytesread = read(fromfd, buf, BLKSIZE)) == -1) &&
(errno == EINTR)) ; /*handle interruption by signal*/
if (bytesread <= 0) /*real error or end-of-file on fromfd*/
break;
bp = buf;
while (bytesread > 0)
{
while(((byteswritten = write(tofd, bp, bytesread)) == -1 )
&&
(errno == EINTR)) ; /*handle interruption by signal*/
if (byteswritten < 0) /*real error on tofd*/
break;
totalbytes += byteswritten;
bytesread -= byteswritten;
bp += byteswritten;
}
if (byteswritten == -1) /*real error on tofd*/
break;
}
return totalbytes;
}
if (argc != 3)
{
fprintf(stderr, "Usage: %s from_file to_file\n", argv[0]);
return 1;
}
if ((fromfd = open(argv[1], READ_FLAGS)) == -1)
{
perror("Failed to open input file");
return 1;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg15 pg15.cpp
Name
read - read from a file descriptor
Synopsis
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Description
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
Return Value
On success, the number of bytes read is returned (zero indicates end of file), and the file
position is advanced by this number
---------------------------
Name
errno - number of last error
Synopsis
#include <errno.h>
Description
The <errno.h> header file defines the integer variable errno, which is set by system calls and some
library functions in the eventof an error to indicate what went wrong. Its value is significant
only when the return value of the call indicated an error (i.e.,-1 from most system calls; -1 or
NULL from most library functions); a function that succeeds is allowed to change errno.
Practical -16
Aim -Write a program for which output is automatically directed to a named file rather than
on to the console
Code –
/*Program to create a file using dup fun (redirect output to some
existing file.)*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include <unistd.h>
int main()
{
int fd;
if((fd=open("test1",O_WRONLY|O_CREAT))<0)
{
printf("Error in opening file..\n");
exit(1);
}
close(1);
dup(fd);
printf("New Fun");
close(fd);
return (0);
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg16 pg16.cpp
CTAE@CTAE-VB:~/osLab$ ./pg16
Name
open- open and possibly create a file
Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
Description
The open() system call opens the file specified by pathname. If thespecified file does not exist, it
may optionally (if O_CREAT isspecified in flags) be created by open().
Return value
open() return the new file descriptor, or -1if an error occurred
-------------------------------------
Name
close - close a file descriptor
Synopsis
#include <unistd.h>
int close(int fd);
Description
close() closes a file descriptor, so that it no longer refers to anyfile and may be reused. Any
record locks (see fcntl(2)) held on thefile it was associated with, and owned by the process, are
removed(regardless of the file descriptor that was used to obtain the lock).
If fd is the last file descriptor referring to the underlying openfile description (see open(2)), the
resources associated with theopen file description are freed; if the file descriptor was the
lastreference to a file which has been removed using unlink(2), the fileis deleted.
Return value
close() returns zero on success. On error, -1 is returned, and errnois set appropriately.
--------------------------------------
Process file descriptor
0->Standard input – STDIN_FILE NO
1->Standard output – STDOUT_FILE NO
2->Standard error – STDERR_FILE NO
--------------------------------------
Name
dup, dup2, dup3 - duplicate a file descriptor
Synopsis
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
Description
The dup() system call creates a copy of the file descriptor oldfd, using the lowest-numbered
unused descriptor for the new descriptor.
The dup2() system call performs the same task as dup(), but instead of using the lowest
numbered unused file descriptor, it usesthe descriptor number specified in newfd. If the
descriptor newfd was previously open, it is silently closed before being reused.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -17
Aim -Write a program that redirects standards output to the file my.file (or Write a program
that do the following operation cat XYZ > myfile). using dup2 rather than dup
Code –
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define CREATE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(void)
{
int fd;
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg17 pg17.cpp
CTAE@CTAE-VB:~/osLab$ ./pg17
CTAE@CTAE-VB:~/osLab$ cat my.file
OK
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
open - open and possibly create a file
Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
Description
Values for flag are constructed by a bitwise-inclusive OR of flags from the following list, defined in
<fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in
the value of oflag:
O_RDONLY Open for reading only.
O_WRONLY Open for writing only.
O_RDWR Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
Practical -18
Aim -Write a program to create an empty directory using system calls
Code –
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
main(int argc, char *argv[])
{
if(argc!=2)
{
printf("Usages: ./a.out directory");
exit(1);
}
if(mkdir(argv[1],744)!=0)
printf("Error in Making Directory");
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg18 pg18.cpp
CTAE@CTAE-VB:~/osLab$ ./pg18 dir1
Name
mkdir - create a directory
Synopsis
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
Description
mkdir() attempts to create a directory named pathname.
The argument mode specifies the mode for the new directorythe newly created directory will be
owned by the effective user ID ofthe process.
The following mask values are defined for the file type:
S_IFMT 0170000 bit mask for the file type bit field
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
Return value
mkdir() and mkdirat() return zero on success, or -1 if an erroroccurred (in which case, errno is set
appropriately).
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -19
Aim -Write a program to remove a directory using system call
Code –
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
main(int argc, char *argv[])
{
if(argc!=2)
{
fprintf(stderr,"Too Less Arguments");
exit(1);
}
if(remove(argv[1])!=0)
fprintf(stderr,"Error in Removing Directory");
exit(1);
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg18 pg18.cpp
CTAE@CTAE-VB:~/osLab$ ./pg18 dir1
Name
rmdir - delete a directory
Synopsis
#include <unistd.h>
int rmdir(const char *pathname);
Description
rmdir() deletes a directory, which must be empty.
remove() can be used to remove a name from the file system.so
remove can be used to remove files and directories. For using remove()we need to include
<stdio.h>.
remove basically calls unlink() for files and rmdir() for directories
We can also use unlink() or rmdir() for removing files or directories respectively directly
inplace of remove(). But remember to include the header file <unistd.h> if you are using
unlink() or rmdir()
Return value
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -20
Aim -Write a program to output current working directory
Code –
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#ifndef PATH_MAX
#define PATH_MAX 255
#endif
int main(void)
{
char mycwd[PATH_MAX];
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg20 pg20.cpp
CTAE@CTAE-VB:~/osLab$ ./pg20
Current working directory: /home/CTAE/osLab
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
getcwd - get current working directory
Synopsis
#include <unistd.h>
char *getcwd(char *buf, size_t size);
Description
These functions return a null-terminated string containing an absolute pathname that is the
current working directory of the calling process.
The getcwd() function copies an absolute pathname of the current working directory to the
array pointed to by buf, which is oflength size.
On failure, these functions return NULL, and errno is set to indicate the error. The contents
of the array pointed to by buf areundefined on error.
Return value
On success, these functions return a pointer to a string containingthe pathname of the current
working directory. In the case getcwd()this is the same value as buf.
On failure, these functions return NULL, and errno is set to indicatethe error. The contents of
the array pointed to by buf are undefinedon error.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -21
Aim -Write a program to list files in a directory.
Code –
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
if (argc != 2)
{
fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
return 1;
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg21 pg21.cpp
CTAE@CTAE-VB:~/osLab$ ./pg21 dir1
test2
test1
..
.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
readdir, readdir_r - read a directory
Synopsis
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
Description
The readdir() function returns a pointer to a dirent structure representing the next directory
entry in the directory streampointed to by dirp. It returns NULL on reaching the end of the directory
stream or if an error occurred.
On Linux, the dirent structure is defined as follows:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supportedby all filesystem types */
char d_name[256]; /* filename */
};
Return value
On success, readdir() returns a pointer to a dirent structure.If the end of the directory stream is
reached, NULL is returned and errno is not changed. If an error occurs, NULL is returned
and errnois set appropriately.
------------------------------------
Name
opendir - open a directory
Synopsis
#include <sys/types.h>
#include <dirent.h>
Description
The opendir() function opens a directory stream corresponding to the directory name, and
returns a pointer to the directory stream.The stream is positioned at the first entry in the
directory.
Return value
The opendir() function return a pointer to the directory stream. On error, NULL is returned,
and errno is setappropriately.
--------------------------------------
Name
closedir - close a directory
Synopsis
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
Description
The closedir() function closes the directory stream associated with dirp. A successful call to
closedir() also closes the underlying file descriptor associated with dirp. The directory stream
descriptor dirp is not available after this call.
Return value
The closedir() function returns 0 on success. On error, -1 is returned, and errno is set
appropriately.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -22
Aim -Write a program that returns true if a given file is a directory & false otherwise.
Code –
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg22 pg22.cpp
CTAE@CTAE-VB:~/osLab$ ./pg22 dir1
dir1 : is a directory
CTAE@CTAE-VB:~/osLab$ ./pg22 test
test : is a file
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
stat - get file status
Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
Description
These functions return information about a file. No permissions are required on the file itself,
but-in the case of stat() and lstat() - execute (search) permission is required on all of the
directories in path that lead to the file.
stat() stats the file pointed to by path and fills in buf
All of these system calls return a stat structure, which contains the following fields:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
The following POSIX macros are defined to check the file type using the st_mode field:
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link?
S_ISSOCK(m) socket?
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -23
Aim -Write a program that can display the type of a given file like regular, directory etc
Code –
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
main(int argc, char *argv[])
{
struct stat statbuff;
int check;
if(argc!=2)
{
printf("Can accept only two arguments");
exit(1);
}
check=stat(argv[1], &statbuff);
if(check==0)
{
if(S_ISREG(statbuff.st_mode))
printf("Regular FIle");
else if(S_ISDIR(statbuff.st_mode))
printf("Directory");
else if(S_ISCHR(statbuff.st_mode))
printf("Char Device");
else
printf("Other File");
}
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg23 pg23.cpp
CTAE@CTAE-VB:~/osLab$ ./pg23 test
Regular FIle
CTAE@CTAE-VB:~/osLab$ ./pg23 dir1
Directory
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
stat - get file status
Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
Description
These functions return information about a file. No permissions are required on the file itself,
but-in the case of stat() and lstat() - execute (search) permission is required on all of the
directories in path that lead to the file.
stat() stats the file pointed to by path and fills in buf
All of these system calls return a stat structure, which contains the following fields:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
The following POSIX macros are defined to check the file type using the st_mode field:
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link?
S_ISSOCK(m) socket?
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -24
Aim -Write a program to display the permission of a given file
Code –
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
main(int argc, char *argv[])
{
struct stat statbuff;
int check;
if(argc!=2)
{
printf("Can Accept only two arguments");
exit(1);
}
check=stat(argv[1], &statbuff);
if(check==0)
{
//check Permission for Owner
if((statbuff.st_mode & S_IRUSR)==S_IRUSR)
printf("Owner has Read Permission\n");
if((statbuff.st_mode & S_IWUSR)==S_IWUSR)
printf("Owner has Write Permission\n");
if((statbuff.st_mode & S_IXUSR)==S_IXUSR)
printf("Owner has Execute Permission\n");
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg24 pg24.cpp
CTAE@CTAE-VB:~/osLab$ ./pg24 test
Owner has Read Permission
Owner has Write Permission
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
sys/stat.h - data returned by the stat() function
Synopsis
#include <sys/stat.h>
Description
The <sys/stat.h> header defines the structure of the data returned by the functions fstat(),
lstat(), and stat().
The structure stat contains at least the following members
dev_t st_dev ID of device containing file
ino_t st_ino file serial number
mode_t st_mode mode of file (see below)
nlink_t st_nlink number of links to the file
uid_t st_uid user ID of file
gid_t st_gid group ID of file
dev_t st_rdev device ID (if file is character or block special)
off_t st_size file size in bytes (if file is a regular file)
time_t st_atime time of last access
time_t st_mtime time of last data modification
time_t st_ctime time of last status change
blksize_t st_blksize a filesystem-specific preferred I/O block size forthis object. In some
filesystem types, this mayvary from file to file
blkcnt_t st_blocks number of blocks allocated for this object
Practical -25
Aim -Write a program to execute the equivalent of ls –l | sort –n +4
Code –
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
pid_t childpid;
int fd[2];
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg25 pg25.cpp
CTAE@CTAE-VB:~/osLab$ ./pg25
Failed to exec sort: No such file or directory
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
Pipe - create pipe
Synopsis
#include <unistd.h>
int pipe(int pipefd[2]);
Description
pipe() creates a pipe, a unidirectional data channel that can be used for interprocess
communication. The array pipefd is used to return two file descriptors referring to the ends of
the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the
pipe. Data written to the write end of the pipe is buffered by the kernel until it is read from the
read end of the pipe
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -26
Aim -Write a program to handle SIGUSR1 and SIGUSR2 signal
Code –
// Program to handle SIGUSR1 and SIGUSR2 interrupt
// Run this prog on background (./a.out&) and kill -s USR1 pid or
//kill USR2 pid to supply these interrupt
//do man 2 signal and understand this function's parameter types and
//return value vary clearly
//do man 2 pause and understand this function's parameter types and
//return value vary clearly
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<signal.h>
#include<unistd.h>
void fun(int);
main()
{
char a[200];
if((signal(SIGUSR1,fun))==SIG_ERR)
{
printf("Handler not registered\n");
exit(1);
}
if((signal(SIGUSR2,fun))==SIG_ERR)
{
printf("Handler not registered\n");
exit(1);
}
while(1)
pause(); // include <unistd.h>
}
void fun(int i)
{
if(i==SIGUSR1)
{
printf("SIGUSR1 INTRRUPT");
fflush(NULL);
}
else if(i==SIGUSR2)
{
printf("SIGUSR2 INTRRUPT");
fflush(NULL);
}
//raise(SIGKILL);
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
signal.h — signals
Synopsis
#include <signal.h>
Description
The following signals shall be supported on all implementations(default actions are explained below
the table):
Output: -
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -27
Aim -Write a program which suspends itself till it receives a SIGALARM signal
Code –
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
void sig_alrm(int);
main(int argc, char *argv[])
{
if((signal(SIGALRM, sig_alrm))==SIG_ERR)
printf("Not Registered");
alarm(5);
pause();
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg27 pg27.cpp
CTAE@CTAE-VB:~/osLab$ ./pg27
Wake Up
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
signal - ANSI C signal handling
Synopsis
#include <signal.h>
typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler);
Description
If the signal signum is delivered to the process, then one of the following happens:
* If the disposition is set to SIG_IGN, then the signal is ignored.
* If the disposition is set to SIG_DFL, then the default action associated with the
signaloccurs.
* If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or
the signal is blocked, and then handler is called with argument signum. If invocation of the
handler caused the signal to be blocked, then the signal is unblocked upon return from the
handler. The signals SIGKILL and SIGSTOP cannot be caught or ignored.
Return value
signal() returns the previous value of the signal handler, or SIG_ERR on error. In the event of an
error, errno is set to indicate the cause.
-----------------------------
Name
alarm - set an alarm clock for delivery of a signal
Synopsis
#include <unistd.h>
unsigned int alarm(unsigned int seconds);
Description
alarm() arranges for a SIGALRM signal to be delivered to the calling process in seconds
seconds.
If seconds is zero, any pending alarm is canceled.
In any event any previously set alarm() is canceled.
Return value
alarm() returns the number of seconds remaining until any previously scheduled alarm was
due to be delivered, or zero if there was no previously scheduled alarm.
---------------------------
Name
pause - wait for signal
Synopsis
#include <unistd.h>
int pause(void);
Description
pause() causes the calling process (or thread) to sleep until a signal is delivered that either
terminates the process or causes the invocation of a signal-catching function.
Return value
pause() returns only when a signal was caught and the signal-catching function returned. In
this case, pause() returns -1, and errno is set to EINTR.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -28
Aim -Write a program which prints the second’s part of current time whenever the
SIGALRM signal is received by the program.
Code –
// After two seconds print TM_SEC field of tm structure using alarm
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<signal.h>
#include<time.h>
#include<unistd.h>
void sig_hand(int);
main()
{
int i=1;
pid_t pid;
if(signal(SIGALRM,sig_hand)==SIG_ERR)
{
printf("Not Registered");
}
while(i<=5)
{
i++;
pid=getpid();
sleep(2);
kill(pid,SIGALRM);
}
}
void sig_hand(int sig)
{
struct tm *t; // this structure can be got by man localtime
time_t tt; // used for time in seconds
if(sig==SIGALRM)
{
tt=time(NULL); //returns current time in sec since epoc (do
//man 2 time)
t=localtime(&tt); // break down time in hr, min, sec, etc
printf("%d\n",t->tm_sec);// new line is necessary here
}
}
Output: -
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
kill - send signal to a process
Synopsis
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
Description
The kill() system call can be used to send any signal to any processgroup or process.
If pid is positive, then signal sig is sent to the process with the ID specified by pid.
If pid equals 0, then sig is sent to every process in the process group of the calling process.
If pid equals -1, then sig is sent to every process for which the calling process has permission
to send signals, except for process 1(init), but see below.
If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid.
If sig is 0, then no signal is sent, but existence and permission checks are still performed; this
can be used to check for the existence of a process ID or process group ID that the caller is
permitted to signal.
Return value
On success (at least one signal was sent), zero is returned. Onerror, -1 is returned, and errno
is set appropriately.
--------------------------
Name
localtime - transform date and time to broken-down time or ASCII
Synopsis
#include <time.h>
struct tm *localtime(const time_t *timep);
Description
localtime() function take an argument of data type time_t which represents calendar time.
When interpreted as an absolute time value, it represents the number of seconds elapsed since
the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
Broken-down time is stored in the structure tm which is defined in <time.h> as follows:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
Return Value
Function returns the value described, or NULL in case an error was detected
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -29
Aim -Write a Program to print the entries of passwd file for a given user name or user ID
Code –
// do man getpwnam to understand getpwnam() function and passwd
structure
// also do cat /etc/passwd file and check what all information is
given in this file
#include<pwd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<signal.h>
#include<time.h>
#include<error.h>
#include<ctype.h>
main()
{
char u_name[10];
char ch;
uid_t u_id;
struct passwd *p;
printf("Enter Your Choice\n");
printf("Whether you want to enter UNAME or UID?(N or I)");
scanf("%c",&ch);
if((ch == 'N')|| (ch == 'n'))
{
printf("Enter UNAME");
scanf("%s",u_name);
p=getpwnam(u_name);
printf("\n%s\n %s\n %d\n %d\n %s\n %s\n %s\n", p-
>pw_name, p->pw_passwd, p->pw_uid,p->pw_gid,p->pw_gecos, p->pw_dir,
p->pw_shell);
}
else if((ch == 'I' || 'i'))
{
printf("Enter UID");
scanf("%d",&u_id);
p= getpwuid (u_id);
printf("\n%s\n %s\n %d\n %d\n %s\n %s\n %s\n", p-
>pw_name, p->pw_passwd, p->pw_uid,p->pw_gid,p->pw_gecos, p->pw_dir,
p->pw_shell);
}
else
printf("Wrong Choice");
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg29 pg29.cpp
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
CTAE@CTAE-VB:~/osLab$ ./pg29
Enter Your Choice
Whether you want to enter UNAME or UID?(N or I)N
Enter UNAME CTAE
-CTAE@CTAE-VB:~$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:103:systemd Network
Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false
syslog:x:104:108::/home/syslog:/bin/false
_apt:x:105:65534::/nonexistent:/bin/false
messagebus:x:106:110::/var/run/dbus:/bin/false
uuidd:x:107:111::/run/uuidd:/bin/false
lightdm:x:108:114:Light Display Manager:/var/lib/lightdm:/bin/false
whoopsie:x:109:117::/nonexistent:/bin/false
avahi-autoipd:x:110:119:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/bin/false
avahi:x:111:120:Avahi mDNS daemon,,,:/var/run/avahi-daemon:/bin/false
dnsmasq:x:112:65534:dnsmasq,,,:/var/lib/misc:/bin/false
colord:x:113:123:colord colour management daemon,,,:/var/lib/colord:/bin/false
speech-dispatcher:x:114:29:Speech Dispatcher,,,:/var/run/speech-
dispatcher:/bin/false
hplip:x:115:7:HPLIP system user,,,:/var/run/hplip:/bin/false
kernoops:x:116:65534:Kernel Oops Tracking Daemon,,,:/:/bin/false
pulse:x:117:124:PulseAudio daemon,,,:/var/run/pulse:/bin/false
rtkit:x:118:126:RealtimeKit,,,:/proc:/bin/false
saned:x:119:127::/var/lib/saned:/bin/false
usbmux:x:120:46:usbmux daemon,,,:/var/lib/usbmux:/bin/false
CTAE:x:1000:1000:CTAE,,,:/home/CTAE:/bin/bash
CTAE
x
1000
1000
CTAE,,,
/home/CTAE
/bin/bash
CTAE@CTAE-VB:~/osLab$ ./pg29
Enter Your Choice
Whether you want to enter UNAME or UID?(N or I)I
Enter UID1000
CTAE
x
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
1000
1000
CTAE,,,
/home/CTAE
/bin/bash
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -30
Aim - Write a program to print the details of the system
Code –
// do man getgrnam to get the information about getgrnam() function
//and structure group
// also do cat /etc/group and check what all information is written
here
#include<grp.h>
#include<stdio.h>
#include<stdlib.h>
main()
{
char g_name[10];
gid_t gid;
char ch;
struct group *g;
printf("Enter Your Choice: \nEnter Group Name(N) \nEnter Group
ID (I)\n");
printf("Enter Choice");
scanf("%c",&ch);
switch(ch)
{
case 'N':
case 'n':
printf("Enter GNAME:");
scanf("%s",g_name);
g=getgrnam(g_name);
printf("\n %s %s %d\n", g->gr_name, g->gr_passwd, g-
>gr_gid);
break;
case 'I':
case 'i':
printf("Enter GID:");
scanf("%d",&gid);
g=getgrgid(gid);
printf("\n %s %s %d\n", g->gr_name, g->gr_passwd, g-
>gr_gid);
break;
default:
printf("Wrong Choice");
}
}
Output: -
CTAE@CTAE-VB:~/osLab$ g++ -o pg30 pg30.cpp
CTAE@CTAE-VB:~/osLab$ id
uid=1000(CTAE) gid=1000(CTAE)
groups=1000(CTAE),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(
lpadmin),128(sambashare)
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
CTAE@CTAE-VB:~/osLab$ ./pg30
Enter Your Choice:
Enter Group Name(N)
Enter Group ID (I)
Enter Choicei
Enter GID:1000
CTAE x 1000
CTAE@CTAE-VB:~/osLab$ ./pg30
Enter Your Choice:
Enter Group Name(N)
Enter Group ID (I)
Enter Choicen
Enter GNAME:CTAE
CTAE x 1000
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Name
getgrnam,getgrgid, - get group file entry
Synopsis
#include <sys/types.h>
#include <grp.h>
struct group *getgrnam(const char *name);
struct group *getgrgid(gid_t gid);
Description
The getgrnam() function returns a pointer to a structure containing the broken-out fields of the
record in the group database (e.g., the local group file /etc/group, NIS, and LDAP) that
matches the group name name.
The getgrgid() function returns a pointer to a structure containing the broken-out fields of the
record in the group database thatmatches the group ID gid.
The group structure is defined in <grp.h> as follows:
struct group {
char *gr_name; /* group name */
char *gr_passwd; /* group password */
gid_t gr_gid; /* group ID */
char **gr_mem; /* NULL-terminated array of pointers
to names of group members */
};
Return value
The getgrnam() and getgrgid() functions return a pointer to a group structure, or NULL if the
matching entry is not found or an error occurs. If an error occurs, errno is set appropriately.
---------------------------------------
CTAE@CTAE-VB:~$ cat /etc/group sasl:x:45:
root:x:0: plugdev:x:46:CTAE
daemon:x:1: staff:x:50:
bin:x:2: games:x:60:users:x:100:
sys:x:3: nogroup:x:65534:
adm:x:4:syslog,CTAE systemd-journal:x:101:
tty:x:5: systemd-timesync:x:102:
disk:x:6: systemd-network:x:103:
lp:x:7: systemd-resolve:x:104:
mail:x:8: systemd-bus-proxy:x:105:
news:x:9: input:x:106:
uucp:x:10: crontab:x:107:
man:x:12: syslog:x:108:
proxy:x:13: netdev:x:109:
kmem:x:15: messagebus:x:110:
dialout:x:20: uuidd:x:111:
fax:x:21: ssl-cert:x:112:
voice:x:22: lpadmin:x:113:CTAE
cdrom:x:24:CTAE lightdm:x:114:
floppy:x:25: nopasswdlogin:x:115:
tape:x:26: ssh:x:116:
sudo:x:27:CTAE whoopsie:x:117:
audio:x:29:pulse mlocate:x:118:
dip:x:30:CTAE avahi-autoipd:x:119:
www-data:x:33: avahi:x:120:
backup:x:34: bluetooth:x:121:
operator:x:37: scanner:x:122:saned
list:x:38: colord:x:123:
irc:x:39: pulse:x:124:
src:x:40: pulse-access:x:125:
gnats:x:41: rtkit:x:126:
shadow:x:42: saned:x:127:
utmp:x:43: CTAE:x:1000:
video:x:44: sambashare:x:128:rubin
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
Practical -31,32
Aim -Write TWO programs
• Q31. Reads what is written to a named pipe & writes it to standard output.
• Q32. Write an informative message to a named pipe
Code 1–
// server
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#define BLKSIZE 1024
#define FIFOARG 1
#define FIFO_PERMS (S_IRWXU | S_IWGRP| S_IWOTH)
for ( ; ; ) {
while (((bytesread = read(fromfd, buf, BLKSIZE)) == -1) &&
(errno == EINTR)) ; /*handle interruption by signal*/
if (bytesread <= 0) /*real error or end-of-file on fromfd*/
break;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur OS Lab
bp = buf;
while (bytesread > 0) {
while(((byteswritten = write(tofd, bp, bytesread)) == -1 )
&&
(errno == EINTR)) ; /*handle interruption by signal*/
if (byteswritten <0) /*real error on tofd*/
break;
totalbytes += byteswritten;
bytesread -= byteswritten;
bp += byteswritten;
}
if (byteswritten == -1) /*real error on tofd*/
break;
}
return totalbytes;
}
Code2 –
//Client
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#define FIFOARG 1
int main (int argc, char *argv[]) {
time_t curtime;
int len;
char requestbuf[PIPE_BUF];
int requestfd;
if (argc != 2) { /* name of server fifo is passed on the command
line */
fprintf(stderr, "Usage: %s fifoname\n", argv[0]);
return 1;
}
if ((requestfd = open(argv[FIFOARG], O_WRONLY)) == -1) {
perror("Client failed to open log fifo for writing");
return 1;
}
curtime = time(NULL);
snprintf(requestbuf, PIPE_BUF, "%d: %s", (int)getpid(),
ctime(&curtime));
len = strlen(requestbuf);
if (write(requestfd, requestbuf, len) != len) {
perror("Client failed to write");
return 1;
}
close(requestfd);
return 0;
}