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

Java Lab Manual

This document contains a lab manual for Object-Oriented Programming through Java. It lists 28 programs to be written in Java, C, shell scripting, and Awk to practice various programming concepts. For each program, it provides the objective, requirements, program logic, sample code, and expected output. The manual was developed by K. Ravi Chythanya, an assistant professor, for a class on OOP through Java.

Uploaded by

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

Java Lab Manual

This document contains a lab manual for Object-Oriented Programming through Java. It lists 28 programs to be written in Java, C, shell scripting, and Awk to practice various programming concepts. For each program, it provides the objective, requirements, program logic, sample code, and expected output. The manual was developed by K. Ravi Chythanya, an assistant professor, for a class on OOP through Java.

Uploaded by

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

OOP through Java Lab Manual K.

Ravi Chythanya

Object-Oriented Programming through Java Lab Manual


Subject Code :
Regulations : R13 – JNTUH
Class : II Year II Semester (CSE)

Developed By:

K. Ravi Chythaya,
Assistant Professor,

-1-
OOP through Java Lab Manual K. Ravi Chythanya

List of Programs
S. No Program’s Name Page No
1) Use eclipse or Netbean platform and acquaint with the various 5
menus, create a test project, add a test class and run it see how you
can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods and classes. Try debug
step by step with a small program of about 10 to 15 lines which
contains at least one if else condition and a for loop.
2) Write a shell script that delete all lines containing a specific word in 6
one or more file supplied as argument to it.
3) Write a shell script that displays a list of all the files in the current 7
directory to which the user has read, write and execute permissions.
4) Write a shell script that receives any number of file names as 8
arguments checks if every argument supplied is a file or a directory
and reports accordingly. Whenever the argument is a file, the number
of lines on it is also reported.
5) Write a shell script that accepts a list of file names as its arguments, 9
counts and reports the occurrence of each word that is present in the
first argument file on other argument files.
6) Write a shell script to list all the directory files in a directory. 10

7) Write a shell script to find factorial of a given integer. 11

8) Write an awk script to count the number of lines in a file that do not 12
contain vowels.
9) Write an awk script to find the number of characters, words and lines 13
in a file.
10) Write a C program that makes a copy of a file using standard I/O and 14
system calls.
11) Write a C Program to Implement the following UNIX commands
using system calls.
A. cat 16
B. ls 17
C. mv 18
12) Write a C program that takes one or more file or directory names as 19
command line input and reports the following information on the file.
1. file type
2. number of links
3. read, write and execute permissions
4. time of last access
13) Write a C program to emulate the Unix ls – l command. 22
14) Write a C program to list for every file in a directory, its inode 24
number and file name.

-2-
OOP through Java Lab Manual K. Ravi Chythanya

15) Write a C program that demonstrates redirection of standard output 26


to a file. Ex: ls >f1.
/* freopen example: redirecting stdout */
16) Write a C program to create a child process and allow the parent to
27
display “parent” and the child to display “child” on the screen.
17) Write a C Program to create a zombie process. 29
18) Write a program that illustrates how an orphan is created. 31
19) Write a c program to illustrate how to execute two commands 32
concurrently with a command pipe. Eg., ls –l | sort
20) Write a C program that illustrates communication between two 34
unrelated processes using named pipe.
21) Write a C program (sender.c) to create a message queue with read
and write permissions to write 3 messages to it with different priority 36
numbers.
22) Write a C program (receiver.c) that receives the messages (from the 38
above message queue as specified in (21)) and displays them.
23) Write a C program to allow cooperating processes to lock a resource 40
for exclusive use, using a) Semaphores b) flock or lockf system calls.
24) Write a C program that illustrates suspending and resuming processes 42
using signals.
25) Write a C program that implements a producer-consumer system 43
with two processes (Using Semaphores).
26) Write client and server programs (using C) for interaction between 45
server and client processes using Unix Domain sockets.
27) Write client and server programs (using C) for interaction between 48
server and client processes using Internet Domain sockets.
28) Write a C Program that illustrates two processes communicating 51
using shared memory.

-3-
OOP through Java Lab Manual K. Ravi Chythanya

-4-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 1
1.1 Objective:
Use eclipse or Netbean platform and acquaint with the various menus, create a test project, add a test
class and run it see how you can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods and classes. Try debug step by step with a small
program of about 10 to 15 lines which contains at least one if else condition and a for loop.
Program:
public class Prog1
{
public static void main(String[] args)
{
System.out.println("\n Program showing even number");
for(int i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n "+i);
}
}
}
}

Compile:-
D:>javac Prog1.java
Run:-
D:>java Prog1

-5-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 2
2.1 Objective:

PROGRAM 3
3.1 Objective:
Write a shell script that displays a list of all the files in the current directory to which the user
has read, write and execute permissions.

3.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

3.3 Program Logic:


Read a list of files from current directory and display the file names to output stream whose files
has read, write, execute permissions.

3.4 Code:
echo -e “Files which has read, write and execute permissions are: \c”
for i in *
do
if [-f $i ]
then
if [ -r $i -a -w $i -a -x $i ]
then
echo “$i”
fi
fi
done

3.5 Output:

-6-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 4
4.1 Objective:
Write a shell script that receives any number of file names as arguments checks if every
argument supplied is a file or a directory and reports accordingly. Whenever the argument is a
file, the number of lines on it is also reported.

4.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

4.3 Program Logic:


Read a list of files from current directory and display the file names to output along with number
of lines of each file.

4.4 Code:
if [ $# -eq 0 ]
then
echo “ Insufficient arguments”
echo “Usage: sh $0 [File]…”
exit 1
fi
for i in $*
do
if [ -f $i ]
then
echo “$i is an ordinary file”
echo “The number of lines in the $i file are: `wc -l $i`”
elif [ -d $i ]
then
echo “$i is a directory”
fi
done

4.5 Output:

-7-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 5
5.1 Objective:
Write a shell script that accepts a list of file names as its arguments, counts and reports the
occurrence of each word that is present in the first argument file on other argument files.

5.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

5.3 Program Logic:


Read list of file names and counts and report the occurrence of each word that is present in the
first argument file on other argument files using comm and grep commands.

5.4 Code:
if [ $# -eq 0 ]
then
echo “Insufficient arguments”
exit 1
fi
f=$1
for i in `cat $f`
do
for j in $*
do
if [ -f $j ]
then
c=`grep -c $i $j`
echo “Number of occurrences of $i in $j is: $c”
else
echo “$j is not a file”
fi
done
done

-8-
OOP through Java Lab Manual K. Ravi Chythanya

5.5 Output:

PROGRAM 6
6.1 Objective:
Write a shell script to list all the directory files in a directory.

6.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

6.3 Program Logic:


1. Read a directory
2. Test given directory is directory file and exist using test options -d
3. If its directory and exist display all the sub directories and files to output stream
4. Else display it is not directory or not exists.

6.4 Code:
echo “Enter a Directory name”
read dir
if [ -d $dir ]
then
cd $dir
echo –e “\n Directories in the directory u entered are…”
echo –e “`ls –l | grep “^d” | cut –d “ “ –f9`”
else
echo “ The directory name U entered is not a directory”
fi

6.5 Output:

-9-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 7
7.1 Objective:
Write a shell script to find factorial of a given number.

7.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

7.3 Program Logic:


1. Read a filename
2. Take a variable i for count and execute expression in for loop, increment the variable
till loop ends,
3. Display the factorial of given number to output stream.

Code:
if [ $# -eq 0 ]
then
echo “Insufficient arguments”
echo “usage: sh $0 the number”
exit 1
fi
fact = 1
n = $1
num = $n
while [ $num –ge 1 ]
do

-10-
OOP through Java Lab Manual K. Ravi Chythanya

fact = `expr $fact /* $num’


num = `expr $num – 1`
done
echo “the factorial of $sum is $fact”

Output:

PROGRAM 8
8.1 Objective:
Write an awk script to count the number of lines in a file that does not contain vowels.

8.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

8.3 Program Logic:


1. Enter the name of file
2. Using awk statement it checks each line to count the number of lines in a file that do not
contain vowels in body part.
3. Display total lines to output stream that do not contain vowels in end part

8.4 Code:
echo “Enter a file name:”
read f1
awk 'BEGIN { line_count = 0 }
!/[aeiou]/ { line_count++; }
END { printf "Number of lines which do not contain vowels= %d\n",line_count }' $f1

8.5 Output:

-11-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 9
9.1 Objective:
Write an awk script to find the number of characters, words and lines in a file.

9.2 Resource/Requirements:
Linux operating system, vi-editor, shell-interpreter

9.3 Program Logic:


1. Enter the file to be searched
2. Using BODY section it checks each line to count the number of lines, Characters, words
in a file.

9.4 Code:

pgm9.sh
echo "enter a file name"
read f1
awk -f "awk9.awk" $f1

awk9.awk

-12-
OOP through Java Lab Manual K. Ravi Chythanya

BEGIN{print "Record\t Characters \t Words"}


#BODY section
{
len=length($0)
total_len+=len
print(NR,"\t",len,"\t\t",NF,"\t",$0)
words+=NF
}
END{ print("Number of Characters: " total_len)
print("Number of Words: " words)
print("Number of Lines: " NR) }

9.5 Output:

PROGRAM 10
10.1 Objective:
Write a C program that makes a copy of a file using standard I/O and system calls.

10.2 Resource/Requirements:
Linux operating system, vi –editor, shell interpreter

10.3 Program Logic:


1. Read source filename, destination filename
2. Open given source filename
3. Read the content from file and write to destination file
4. Repeat step 3 till end of file reaches
5. Close open files

10.4 Code:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define SIZE 1024

-13-
OOP through Java Lab Manual K. Ravi Chythanya

#define MODE(S_IRUSR| S_IWUSR| S_IRGRP | S_IROTH)


void main(int argc, char *argv[])
{
int src, dst;
int in_cnt, out_cnt;
char buf[SIZE];
int nread;
if(argc!=3)
{
printf(“Usage: CP f1 f2 \n”);
exit(1);
}
if((src=opern(argv[1], O_RDONLY))== -1)
{
printf(“The file cannot be opened: %s \n”, argv[1]);
exit(2);
}
if((dst=create(argv[2],MODE))==-1)
{
printf(“The destination file cannot be created: %s \n” argv[2]);
exit(3);
}
while(nread=read(src,buf,SIZE))>0)
{
if(write(dst,buf,nread)==-1)
{
printf(“Cannot write\n”);
exit(4);
}
}
}

10.5 Output:

-14-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 11.A
11. A .1 Objective:
Write a C Program to Implement the UNIX command cat using system calls.

11. A. 2 Resource/Requirements:
Linux operating system, vi –editor, shell interpreter

-15-
OOP through Java Lab Manual K. Ravi Chythanya

11. A. 3 Program Logic:


1. Open file which is input given by command line arguments
2. Read content from opened file
3. Display content to output stream
4. Repeat step 2 and step 3 till end of file reach

11. A. 4 Code:
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[3] )
{
int fd,i;
char buf[2];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-argc)
printf("file open error");
else
{
while(i=read(fd,buf,1)>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}

11. A. 5 Output:

PROGRAM 11.B
11. B. 1 Objective:
Write a C Program to Implement the UNIX command ls using system calls

11. B. 2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

-16-
OOP through Java Lab Manual K. Ravi Chythanya

11. B. 3 Program Logic:


1. Open a directory of given directory name
2. Scan directory and Read file and display filename to output stream
3. Repeat step 2 till End of directory reach.

11. B.4 Code:


#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/dir.h>
#include<sys/stat.h>
main()
{
char dirname[10];
DIR *p;
struct dirent *d;
printf("Enter directory name ");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find dir.");
exit(-1);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
}

11. B. 5 Output:

PROGRAM 11.C
11. C. 1 Objective:
To write a C Program to Implement the UNIX command ‘mv’ using system calls.

11. C. 2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

-17-
OOP through Java Lab Manual K. Ravi Chythanya

11. C. 3 Program Logic:


1. Open two files. Read and write mode respectively.
2. Using rename function move file content to another file
3. Remove source file using unlink() function.

11. C. 4 Code
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}

11. C. 5 Output:

PROGRAM 12
12. 1 Objective:
Write a C program that takes one or more file or directory names as command line input and
reports the following information on the file.
1. file type
2. number of links

-18-
OOP through Java Lab Manual K. Ravi Chythanya

3. read, write and execute permissions


4. time of last access
(Note: use /fstat system calls)

12.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

12. 3 Program Logic:


1. Open a file using fopen() function
2. Read a file and display a file properties to output stream.

12.4 Code:
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char * error_msg[] = { "\nUsage: ./12filestat <file|dir> [<file|dir>]\n\n",
"\nFile does not exist !!\n\n",
"\nError doing 'stat' on file\n\n" };
void print_error(int msg_num, int exit_code, int exit_flag);
int main(int argc, char *argv[])
{
int i;
mode_t file_perm;
struct stat file_details;
char success_msg[] = "\nCommand executed successfully\n\n";
if ( argc < 2 ) print_error(0,2,1);
for ( i = 1; i < argc; i++ )
{
printf("\n%s\n%s\n%s\n","----------------",argv[i],"----------------");
if ( access(argv[i],F_OK) == -1 )
{
print_error(1,3,0);
continue;
}
if ( lstat(argv[i],&file_details) < 0 )
{
print_error(2,4,0);
continue;
}
if ( S_ISREG(file_details.st_mode) )
printf("File type : Regular\n");
else if ( S_ISDIR(file_details.st_mode) )
printf("File type : Directory\n");
else if ( S_ISLNK(file_details.st_mode) )

-19-
OOP through Java Lab Manual K. Ravi Chythanya

printf("File type : Symbolic link\n");


else
printf("File type : Other");
printf("Number of links : %d\n", (int)file_details.st_nlink);
printf("Time of last access : %s", ctime(&file_details.st_atime));
printf("File Permissions:\n");
file_perm = file_details.st_mode & ~S_IFMT;
printf("\tUser : ");
if ( file_perm & S_IRUSR )
printf("Readable, ");
else
printf("Not readable, ");
if ( file_perm & S_IWUSR )
printf("Writable, ");
else
printf("Not writable, ");
if ( file_perm & S_IXUSR )
printf("Executable\n");
else
printf("Not executable\n");
printf("\tGroup : ");
if ( file_perm & S_IRGRP )
printf("Readable, ");
else
printf("Not readable, ");
if ( file_perm & S_IWGRP )
printf("Writable, ");
else
printf("Not writable, ");
if ( file_perm & S_IXGRP )
printf("Executable\n");
else
printf("Not executable\n");
printf("\tOthers : ");
if ( file_perm & S_IROTH )
printf("Readable, ");
else
printf("Not readable, ");
if ( file_perm & S_IWOTH )
printf("Writable, ");
else
printf("Not writable, ");
if ( file_perm & S_IXOTH )
printf("Executable\n");
else
printf("Not executable\n"); }

-20-
OOP through Java Lab Manual K. Ravi Chythanya

printf("%s", success_msg);
return 1;
}
void print_error(int error_index, int exit_code, int exit_flag)
{
fprintf(stderr, "%s\n",error_msg[error_index]);
if (exit_flag)
exit(exit_code);
}

12.5 Output:

PROGRAM 13
13.1 Objective:
Write a C program to emulate the Unix ls – l command.

13.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

-21-
OOP through Java Lab Manual K. Ravi Chythanya

13.3 Program Logic:


1. Declare and initialize required objects.
2. Read the directory name form the user.
3. Open the directory using opendir() system call and report error if the directory is not
available.
4. Read the entry available in the directory.
5. Display the directory entry ie., name of the file or sub directory.
6. Repeat the step 6 and 7 until all the entries were read.

13.4 Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int pid; //process id
pid=fork(); //create another process
if(pid<0)
{ //fail
printf("Fork failed");
exit(-1);
}
else if(pid==0)
{ //child
execlp("/bin/ls","ls","-l",NULL); //execute ls
}
else
{ //parent
wait(NULL); //wait for child
printf("child complete");
exit(0);
}
}

13.5 Output:

-22-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 14

-23-
OOP through Java Lab Manual K. Ravi Chythanya

14.1 Objective:
Write a C program to list for every file in a directory, its inode number and file name.

14.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

14.3 Program Logic:


1. Read Directory name as input
2. Scan entire directory and display its directory file name and inode number till EOF of the
directory

14.4 Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
struct stat sb;
if (argc != 2)
{
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (stat(argv[1], &sb) == -1)
{
perror("stat");
exit(EXIT_FAILURE);
}
printf("File type: ");
switch (sb.st_mode & S_IFMT)
{
case S_IFBLK: printf("block device\n");
break;
case S_IFCHR: printf("character device\n");
break;
case S_IFDIR: printf("directory\n");
break;
case S_IFIFO: printf("FIFO/pipe\n");
break;
case S_IFLNK: printf("symlink\n");
break;
case S_IFREG: printf("regular file\n");
break;
case S_IFSOCK: printf("socket\n");
break;

-24-
OOP through Java Lab Manual K. Ravi Chythanya

default: printf("unknown?\n");
break;
}
printf("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n", (unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n", (long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n", (long) sb.st_blksize);
printf("File size: %lld bytes\n", (long long) sb.st_size);
printf("Blocks allocated: %lld\n", (long long) sb.st_blocks);
printf("Last status change: %s\n", ctime(&sb.st_ctime));
printf("Last file access: %s\n", ctime(&sb.st_atime));
printf("Last file modification: %s\n", ctime(&sb.st_mtime));
exit(EXIT_SUCCESS);
}

14.5 Output:

PROGRAM 15

-25-
OOP through Java Lab Manual K. Ravi Chythanya

15.1 Objective:
Write a C program that demonstrates redirection of standard output to a file. Ex: ls >f1.
/* freopen example: redirecting stdout */

15.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

15.3 Program Logic:


1. Open file using freopen() function
2. Redirect of standard to output to a new file

15.4 Code:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *stream ;
if((stream = freopen("file.txt", "w", stdout)) == NULL)
exit(-1);
printf("this is stdout output\n");
stream = freopen("CON", "w", stdout);
printf("And now back to the console once again\n");
}

15.5 Output:

PROGRAM 16

-26-
OOP through Java Lab Manual K. Ravi Chythanya

16.1 Objective:
To write a C program to create a child process and allow the parent to display “parent” and the
child to display “child” on the screen.

16.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

16.3 Program Logic:


1. Create child process using fork() function
2. If pid is not equal to zero execute parent block
3. else if pid is equal to zero execute child block
4. Display process id using getpid() and parent process id getppid() functions.

16.4 Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int pid;
int p[2];
int q[2];
int a;
int b;
a = pipe(p);
if(a == -1)
{
fprintf(stderr, "Pipe Failed.\n");
return EXIT_FAILURE;
}
b = pipe(q);
if(b == -1)
{
fprintf(stderr, "Pipe Failed.\n");
return EXIT_FAILURE;
}
pid = fork();
switch(pid)
{
case -1: perror("main: fork");
exit(1);
case 0: printf("Child process ID: %d\n", pid);
break;
default: printf("Parent process ID: %d\n", pid);
break;
}
getchar();

-27-
OOP through Java Lab Manual K. Ravi Chythanya

return 0;
}
16.5 Output:

PROGRAM 17

-28-
OOP through Java Lab Manual K. Ravi Chythanya

17.1 Objective:
To write a C program to create a Zombie process.

17.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

17.3 Program Logic:


1. Create a new child process using fork()
2. If pid is not equal to zero execute parent process and block the process 60 seconds
3. If pid is equal to zero executer child process and terminate immediately
4. To see already terminated process i.e zombie process open new command prompt and
type ps -a it shows status z means that process is zombie process.

17.5 Code:

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
child_pid = fork ();
if (child_pid > 0) {
sleep (60);
}
else
{
exit (0);
}
return 0;
}

Output:
Save it as pgm17.c, compile it with:

Code:
cc -o pgm17 pgm17.c

and run it with the following command:


./pgm17

Now check the output of this command (within 1 minute) in another window:

Code:
ps -e -o pid,ppid,stat,cmd

The child process is marked as <defunct>, and its status code is Z, for zombie.

-29-
OOP through Java Lab Manual K. Ravi Chythanya

When the program exits, the child process is inherited by init. This process should cleans up the
zombie proces automatically.

PROGRAM 18

-30-
OOP through Java Lab Manual K. Ravi Chythanya

18.1 Objective:
To write a C program that illustrates how an orphan is created.

18.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

18.3 Program Logic:


1. Create a new child process using fork()
2. If pid is not equal to zero execute parent process block of code and terminates
3. If pid is equal to zero executer child process and block process for 5 seconds in mean
time parent process terminates.
4. To see child process is became orphan process open new command prompt and type ps -a
it shows status O means that process is orphan process.

18.5 Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
pid_t i;
i=fork();
if (i==0)
{
printf("child process pid = %d, ppid=%d\n",(int)getpid(), (int)getppid());
sleep(3);
}
else
{
printf("parent has finished");
}
return 0;
}

Output:

PROGRAM 19

-31-
OOP through Java Lab Manual K. Ravi Chythanya

19.1 Objective:
Write a C program that illustrates how to execute two commands concurrently with a command
pipe. Eg. ls-l|sort.

19.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

19.3 Program Logic:


1. Open a directory of given directory name
2. Scan directory and Read file and display filename to output stream
3. Repeat step 2 till eof directory reach.
4. Using stat function test type of file, its permissions and file properties and display to
output stream.

19.4 Code:
#include <stdio.h>
int main(void)
{
FILE *pipein_fp, *pipeout_fp;
char readbuf[80];

/* Create one way pipe line with call to popen() */


if (( pipein_fp = popen("ls", "r")) == NULL)
{
perror("popen");
exit(1);
}

/* Create one way pipe line with call to popen() */


if (( pipeout_fp = popen("sort", "w")) == NULL)
{
perror("popen");
exit(1);
}

/* Processing loop */
while(fgets(readbuf, 80, pipein_fp))
fputs(readbuf, pipeout_fp);

/* Close the pipes */


pclose(pipein_fp);
pclose(pipeout_fp);
return(0);
}

19.5. Output:

-32-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 20

-33-
OOP through Java Lab Manual K. Ravi Chythanya

20.1 Objective:
Write a C program that illustrates communication between two unrelated processes using named
pipe.

20.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

20.3 Code:
//pgm20r.c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}

//pgm20w.c
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666);
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
unlink(myfifo);
return 0;
}

20.4. Output:

-34-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 21

-35-
OOP through Java Lab Manual K. Ravi Chythanya

21.1 Objective:
Write a C program (sender.c) to create a message queue with read and write permissions to write
3 messages to it with different priority numbers.

21.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

21.3 Program Logic:


1. Create process using msgget(), identify process using a key
2. Declare structure to store message and message type.
3. Using msgsnd() function write a message to message queue.

21.4 Code:
pgm21.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int qid,len,i;
char s[15];
struct
{
long mtype;
char mtext[15];
}
message,buff;
qid=msgget((key_t)10,IPC_CREAT|0666);
if(qid==-1)
{
perror("message queue create failed");
exit(1);
}
for(i=1;i<=3;i++)
{
printf("Enter the message to send\n");
scanf("%s",s);
strcpy(message.mtext,s);
message.mtype=i;
len=strlen(message.mtext);
if(msgsnd(qid,&message,len+1,0)==-1)
{
perror("message failed\n");
exit(1);

-36-
OOP through Java Lab Manual K. Ravi Chythanya

}
}
}

21.5 Output:

PROGRAM 22

-37-
OOP through Java Lab Manual K. Ravi Chythanya

22.1 Objective:
Write a C program (receiver.c) that receives the messages (from the above message queue as
specified in (21)) and displays them.

22.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

22.3 Program Logic:


1. Connect client and server with socket() function.
2. Provide socket address (port, ip-address).
3. Use connect() and bind(), listen() in client and server respectively.
4. If successful use accept() in server.
5. Use fprintf() and read() for sending and receiving the data for communication between
server and client.
6. Close the connection

22.4 Code:
pgm22.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int qid,len,i;
char s[15];
struct
{
long mtype;
char mtext[15];
}buff;
qid=msgget((key_t)10,IPC_CREAT|0666);
if(qid==-1)
{
perror("message queue create failed");
exit(0);
}
for(i=1;i<=3;i++)
{
if(msgrcv(qid,&buff,15,i,0)==-1)
{
perror("message failed\n");
exit(0);
}
printf("Message received from sender is %s\n",buff.mtext);

-38-
OOP through Java Lab Manual K. Ravi Chythanya

}
}

22.5 Output:

PROGRAM 23

-39-
OOP through Java Lab Manual K. Ravi Chythanya

23.1 Objective:
Write a C program to allow cooperating processes to lock a resource for exclusive use, using
a) Semaphores b) flock or lockf system calls.

23.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

23.3 Program Logic:


1. Create semaphore and create key using flck() function
2. Use semctl() to control the process.

23.4 Code:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char* argv[])
{
struct flock f1={f_wrlck,seek_set,0,0,0);
int fd;
f1.l_type=f_rdlck;
if((fd=open(‘rr.txt”,o_rdwr))==-1)
{
perror(“open”);
exit(1);
}
printf(“press<return> to try to get lock:”);
getchar();
printf(“trying to get lock”):
if(fnctl(fd,f_setlkw,&f1)==-1)
{
perror(“fcntl”);
exit(1);
}
printf(“got lock \n”);
printf(“press <return> to release lock:”);
getchar( );
f1.l_type=f_unlck;
if(fcntl(fd,f_setlk,&f1)==-1)
{
perror(“fcntl”);
exit(1);
}
printf(“unlocked\n”);
close(fd);
}

23.5 Output:

-40-
OOP through Java Lab Manual K. Ravi Chythanya

PROGRAM 24

-41-
OOP through Java Lab Manual K. Ravi Chythanya

24.1 Objective:
Write a C program that illustrates suspending and resuming processes using signals.

24.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

24.3 Code:
#include <stdio.h>
#include <ospace/unix.h>
int child_function()
{
while (true) // Loop forever
{
printf("Child loop\n");
os_this_process::sleep( 1 );
}
return 0; // Will never execute.
}
int main()
{
os_unix_toolkit initialize;
os_process child ( child function ); // Spawn child.
os_this_process::sleep( 4 );
printf("child.suspend()\n");
child.suspend();
printf("Parent sleeps for 4 seconds\n");
os_this_process::sleep (4);
printf("child.resume()");
child.resume ();
os_this_process::sleep (4);
printf("child.terminate()");
child.terminate ();
printf("Parent finished");
return 0;
}

24.4 Output:

PROGRAM 25

-42-
OOP through Java Lab Manual K. Ravi Chythanya

25.1 Objective:
Write a C program that implements a producer-consumer system with two processes (Using
Semaphores).

25.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

25.3 Program Logic:


1. Create semaphore using semget( ) system call
2. If successful it returns positive value
3. Create two new processes
4. First process will produce
5. Until first process produces second process cannot consume

25.4 Code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<unistd.h>
#define num_loops 2
int main(int argc,char* argv[])
{
int sem_set_id;
int child_pid,i,sem_val;
struct sembuf sem_op;
int rc;
struct timespec delay;
sem_set_id=semget(ipc_private,2,0600);
if(sem_set_id==-1)
{
perror(“main:semget”);
exit(1);
}
printf(“semaphore set created,semaphore setid‘%d’\n ”, sem_set_id);
child_pid=fork();
switch(child_pid)
{
case -1: perror(“fork”);
exit(1);
case 0:
for(i=0;i<num_loops;i++)
{
sem_op.sem_num=0;
sem_op.sem_op=-1;
sem_op.sem_flg=0;

-43-
OOP through Java Lab Manual K. Ravi Chythanya

semop(sem_set_id,&sem_op,1);
printf(“producer:’%d’\n”,i);
fflush(stdout);
}
break;
default:
for(i=0;i<num_loops;i++)
{
printf(“consumer:’%d’\n”,i);
fflush(stdout);
sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
semop(sem_set_id,&sem_op,1);
if(rand()>3*(rano_max14));
{
delay.tv_sec=0;
delay.tv_nsec=10;
nanosleep(&delay,null);
}
}
break;
}
return 0;
}
25.5 Output:

PROGRAM 26
26.1 Objective:

-44-
OOP through Java Lab Manual K. Ravi Chythanya

Write client and server programs (using C) for interaction between server and client processes
using Unix Domain sockets.

26.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

26.3 Program Logic:


1. Create socket at client side and server side for communication.
2. Server side execute bind and accept function to accept client
3. Client side execute connect function to establish connection between client and server
4. Exchange information through unix domain sockets.
5. Close socket file descriptor after completion of communication.

26.4 Code:
Client:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
struct sockaddr_un address;
int socket_fd, nbytes;
char buffer[256];
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf("socket() failed\n");
return 1;
} /* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(connect(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0)
{
printf("connect() failed\n");
return 1;
}
nbytes = snprintf(buffer, 256, "hello from a client");
write(socket_fd, buffer, nbytes);
nbytes = read(socket_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM SERVER: %s\n", buffer);
close(socket_fd);
return 0;
}

-45-
OOP through Java Lab Manual K. Ravi Chythanya

Server:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int connection_handler(int connection_fd)
{
int nbytes;
char buffer[256];
nbytes = read(connection_fd, buffer, 256);
buffer[nbytes] = 0;
printf(“MESSAGE FROM CLIENT: %s\n”, buffer);
nbytes = snprintf(buffer, 256, “hello from the server”);
write(connection_fd, buffer, nbytes);
close(connection_fd);
return 0;
}
int main(void)
{
struct sockaddr_un address;
int socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf(“socket() failed\n”);
return 1;
}
unlink(“./demo_socket”); /* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0)
{
printf(“bind() failed\n”);
return 1;
}
if(listen(socket_fd, 5) != 0)
{
printf(“listen() failed\n”);
return 1;
}

-46-
OOP through Java Lab Manual K. Ravi Chythanya

while((connection_fd = accept(socket_fd, (struct sockaddr *) &address,


&address_length)) > -1)
{
child = fork();
if(child == 0)
{ /* now inside newly created connection handling process */
return connection_handler(connection_fd);
}/* still inside server process */
close(connection_fd);
}
close(socket_fd);
unlink(“./demo_socket”);
return 0;
}

26.5 Output:

At Server Side

At Client Side

PROGRAM 27

-47-
OOP through Java Lab Manual K. Ravi Chythanya

27.1 Objective:
Write client and server programs (using C) for interaction between server and client processes
using Internet Domain sockets.

27.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

27.3 Program Logic:


1. Connect client and server with socket() fuction.
2. Provide socket address (port, ip-address) of Internet Domain Sockets.
3. Use connect() and bind(), listen() in client and server respectively.
4. If successful use accept() in server.
5. Use fprintf() and read() for sending and receiving the data for communication between
server and client.
6. Close the connection

27.4 Code:
Client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3)
{
fprintf(stderr,“usage %s hostname port\n”, argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error(“ERROR opening socket”);
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,“ERROR, no such host\n”);

-48-
OOP through Java Lab Manual K. Ravi Chythanya

exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error(“ERROR connecting”);
printf(“Please enter the message: ”);
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error(“ERROR writing to socket”);
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error(“ERROR reading from socket”);
printf(“%s\n”,buffer);
return 0;
}
Server.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2)
{
fprintf(stderr,“ERROR, no port provided\n”);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error(“ERROR opening socket”);
bzero((char *) &serv_addr, sizeof(serv_addr));

-49-
OOP through Java Lab Manual K. Ravi Chythanya

portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error(“ERROR on binding”);
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error(“ERROR on accept”);
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0)
error(“ERROR reading from socket”);
printf(“Here is the message: %s\n”,buffer);
n = write(newsockfd,”I got your message”,18);
if (n < 0)
error(“ERROR writing to socket”);
return 0;
}

27.5 Output:

At Client Side

At Server Side
PROGRAM 28
28.1 Objective:

-50-
OOP through Java Lab Manual K. Ravi Chythanya

Write a C Program that illustrates two processes communicating using shared memory.

28.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler

28.3 Program Logic:


1. Create two process ,
2. Use shmget() to connect the processes.
3. Take a memory and attach this two process using shmat()
4. Now both the process can access the common memory.

28.4 Code:
#include<stdio.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<sys/shm.h>
#define SIZE 5*1024
int main()
{
char *ptr;
int shmid,pid,n;
shmid=shmget((key_t)10,30,IPC_CREAT|0666);
ptr=(char *)shmat(shmid,(char *)0,0);
pid=fork();
if(pid==0)
{
n=read(0,ptr,SIZE);
ptr[n]='\0';
}
else
{
wait(0) ;
printf(“parent read from shared memory\n”);
write(1,ptr,strlen(ptr));
}
}

28.5 Output:

-51-
OOP through Java Lab Manual K. Ravi Chythanya

-52-

You might also like