Java Lab Manual
Java Lab Manual
Ravi Chythanya
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
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
-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.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.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.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.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
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
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.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.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
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.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
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. 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. 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. 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
12.2 Resource/Requirements:
Linux operating system, vi –editor, c-compiler
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
-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.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.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.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.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.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
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.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.4 Code:
#include <stdio.h>
int main(void)
{
FILE *pipein_fp, *pipeout_fp;
char readbuf[80];
/* Processing loop */
while(fgets(readbuf, 80, pipein_fp))
fputs(readbuf, pipeout_fp);
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.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.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.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.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.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
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.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.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-