You are on page 1of 42

LINUX PROGRAMMING LAB MANUAL

Contents
Page
S.No Name of the Program
no

Write a shell script that accepts a file name, starting and ending line numbers as
1 3
arguments and displays all the lines between the given line numbers.
Write a shell script that deletes all lines containing a specified word in one or
2 4
more files supplied as arguments to it.
Write a shell script that displays a list of all the files in the current directory to
3 5
which the user has read, write and execute permissions.
Write a shell script that receives any number of file names as arguments checks if
4 every argument supplied is a file or a directory and reports accordingly. 6
Whenever the argument is a file, the number of lines on it is also reported.
Write a shell script that accepts a list of file names as its arguments, counts and
5 reports the occurrence of each word that is present in the first argument file on 7
other argument files

6 Write a shell script to list all of the directory files in a directory. 8

Write a shell script to find factorial of a given integer.


7 8

Write an awk script to count the number of lines in a file that do not contain
8 9
vowels.

9 Write an awk script to find the number of characters, words and lines in a file. 10

Write a c program that makes a copy of a file using standard I/O and system calls
10 11

Implement in C the following UNIX commands using System calls


11 12
A. cat B. ls C. mv

Write a C program to list files in the directory.


12 15

13 Write a C program to emulate the UNIX ls l command. 16


Write a C program to list for every file in a directory, its inode number and file
14 17
name.
Write a C program that demonstrates redirection of standard output to a file.
15 25
Ex: ls > f1.
16 Write a C program to create a child process and allow the parent to display
26
parent and the child to display child on the screen.

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 1


LINUX PROGRAMMING LAB MANUAL

17 Write a C program to create a Zombie process. 27

18 Write a C program that illustrates how an orphan is created. 28

Write a C program that illustrates how to execute two commands concurrently


19
with a command pipe. 29
Ex: - ls l | sort

Write C programs that illustrate communication between two unrelated processes


20 32
using named pipe

Write a C program to create a child process and allow the parent to display
21 parent and the child to display child on the screen. 35

Write a C program to create a message queue with read and write permissions to
22 36
write 3 messages to it with different priority numbers.

Write a C program that receives the messages (from the above message queue as
23 37
specified in (22)) and displays them.

Write a C program that illustrates suspending and resuming processes using


24 40
signals

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

Write client and server programs (using c) for interaction between server and
26. 44
client processes using Internet Domain sockets.

Write a C program that illustrates two processes communicating using shared


27 47
memory

1. Write a shell script that accepts a file name, starting and ending line numbers as
arguments and displays all the lines between the given line numbers.

Aim: To Write a shell script that accepts a file name, starting and ending line numbers as
arguments and displays all the lines between the given line numbers.

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 2


LINUX PROGRAMMING LAB MANUAL

Script:
$ awk NR<2 || NR> 4 {print $0} 5 lines.dat

I/P: line1
line2
line3
line4
line5

O/P: line1
line5

or

#!/bin/sh

echo Enter file name

read file

echo First Line displays :

head -1 $file

echo Last line displays :

tail -1 $file

echo Displays all lines in a given file :

cat $file

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 3


LINUX PROGRAMMING LAB MANUAL

2. Write a shell script that deletes all lines containing a specified word in one or more
files supplied as arguments to it.

Aim: To write a shell script that deletes all lines containing a specified word in one or more
files supplied as arguments to it.

Script:

sed -e '/word/d' file1 file2 file3 > file.out

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 4


LINUX PROGRAMMING LAB MANUAL

3. 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.

Aim: To 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.

Script:

echo "List of Files which have Read, Write and Execute Permissions in Current
Directory"

for file in *

do

if [ -r $file -a -w $file -a -x $file ]

then

echo $file

fi

done

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 5


LINUX PROGRAMMING LAB MANUAL

4. 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

Aim: To write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or a directory

Script:

echo enter file name

read file

echo reads file files and displays in

wc l $file

wc w $file

wc c $file

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 6


LINUX PROGRAMMING LAB MANUAL

5. 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.

Aim : To 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.

Script:

echo Enter file or dir name

read file

if [ -d $file ]

then

echo given name is directory

elif [ -f $file ]

then

echo given name is file: $file

echo No of lines in file are : wc l $file

else

echo given name is not a file or a directory


fi

6. Write a shell script to list all of the directory files in a directory.

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 7


LINUX PROGRAMMING LAB MANUAL

Script:
# !/bin/bash
echo"enter directory name"
read dir
if[ -d $dir]
then
echo"list of files in the directory"
ls $dir
else
echo"enter proper directory name"
fi
Output:
Enter directory name
Atri
List of all files in the directoty
CSE.txt
ECE.txt

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 8


LINUX PROGRAMMING LAB MANUAL

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

Script:
echo Factorial

echo "Enter a number: "

read f

fact=1

factorial=1

while [ $fact -le $f ]

do

factorial=`expr $factorial \* $fact`

fact=`expr $fact + 1`

done

echo "Factorial of $f = $factorial"

Output:
Enter a number
5
Factorial of 5 is 120

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 9


LINUX PROGRAMMING LAB MANUAL

8. Write an awk script to count the number of lines in a file that do not contain vowels.

#!/bin/bash
echo "Enter file name"
read file
awk '$0!~/[aeiou]/{ count++ }
END{print "The number of lines that does not contain vowels are: ",count}' $file

Output

Enter file name


test1
The number of lines that does not contain vowels are: 3

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 10


LINUX PROGRAMMING LAB MANUAL

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

Aim : To write an awk script to find the number of characters, words and lines in a file.

Script:
BEGIN{print "record.\t characters \t words"}

#BODY section

len=length($0)

total_len+=len

print(NR,":\t",len,":\t",NF,$0)

words= words+NF

END{

print("\n total")

print("characters :\t" total_len)

print("words :\t" words)

print("lines :\t" NR)

output:
$ vi ex
this is an example of awk
counting vowels
not containing in lines

$ awk f count.awk ex

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 11


LINUX PROGRAMMING LAB MANUAL

record. characters words


1: 25 : 6 this is an example of awk
2: 15 : 2 counting vowels
3: 23 : 4 not containing in lines

total
characters : 63
words: 12
lines : 3

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 12


LINUX PROGRAMMING LAB MANUAL

10. Write a c program that makes a copy of a file using standard I/O and system calls

#include<stdlib.h>

#include<stdio.h>

#include <unistd.h>

#include <fcntl.h>

int main(int argc, char *argv[])

int fd1, fd2;

char buffer[100];

long int n1;

if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2=open(argv[2],O_CREAT|O_WRONLY|


O_TRUNC,

0700)) == -1)){

perror("file problem ");

exit(1);

while((n1=read(fd1, buffer, 100)) > 0)

if(write(fd2, buffer, n1) != n1){

perror("writing problem ");

exit(3);

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 13


LINUX PROGRAMMING LAB MANUAL

$ cat del
unix is os
dos is also os
here using unix
unix is powerful os

$ cc lp10.c

$ ./a.out del exdel

$ cat exdel
unix is os
dos is also os
here using unix
unix is powerful os

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 14


LINUX PROGRAMMING LAB MANUAL

11. Implement in C the following UNIX commands using System calls


A. cat B. ls C. mv

AIM: Implement in C the cat Unix command using system calls

A. cat

#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);
}
}

output:
$cc cat.c
$./a.out sample

c.mv

#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);

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 15


LINUX PROGRAMMING LAB MANUAL

while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}

output:
$cc mv.c
$cat > ff
hello
hai
$./a.out ff ff1
$cat ff
cat:ff:No such file or directory
$cat ff1
hello
hai

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 16


LINUX PROGRAMMING LAB MANUAL

12. Write a C program to list files in the directory.

#include <dirent.h>
#include <stdio.h>

int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}

closedir(d);
}

return(0);
}

cc prog12.c
./a.out

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 17


LINUX PROGRAMMING LAB MANUAL

13. Write a C program to emulate the UNIX ls l command.

#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(\nFork failed\n);
exit (-1);
}
else if ( pid == 0 )
{ //child
execlp ( /bin/ls, ls, -l, NULL ); //execute ls
}
else
{ //parent
wait (NULL); //wait for child
printf(\nchild complete\n);
exit (0);
}
}

SAMPLE OUTPUT:

cc prog13.c

./a.out

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 18


LINUX PROGRAMMING LAB MANUAL

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

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
main(int argc, char *argv[])
{
char d[50];
if(argc==2)
{
bzero(d,sizeof(d));
strcat(d,"ls ");
strcat(d,"-i ");
strcat(d,argv[1]);
system(d);
}
else
printf("\nInvalid No. of inputs");
}

output:

$cc prog14.c

./a.out hello

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 19


LINUX PROGRAMMING LAB MANUAL

15. Write a C program that demonstrates redirection of standard output to a file.


Ex: ls > f1.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
main(int argc, char *argv[])
{
char d[50];
if(argc==2)
{
bzero(d,sizeof(d));
strcat(d,"ls ");
strcat(d,"> ");
strcat(d,argv[1]);
system(d);
}
else
printf("\nInvalid No. of inputs");
}

Output:
$ gcc o prog15.out prog15.c
$ls
downloads documents listing.c listing.out prog15.c
prog15.out
$ cat > f1
^z
$./prog15.out f1
$cat f1
downloads
documents
listing.c
listing.out
std.c
std.out

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 20


LINUX PROGRAMMING LAB MANUAL

16. 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.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int childpid;

if (( childpid=fork())<0)
{
printf("cannot fork");
}
else if(childpid >0)
{

}
else
printf(Child process);
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 21


LINUX PROGRAMMING LAB MANUAL

17. Write a C program to create a Zombie process.


If child terminates before the parent process then parent process with out child is called
zombie process

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int childpid;

if (( childpid=fork())<0)
{
printf("cannot fork");
}
else if(childpid >0)
{
Printf(child process);
exit(0);

}
else
{
wait(100);
printf(parent process);
}
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 22


LINUX PROGRAMMING LAB MANUAL

18. Write a C program that illustrates how an orphan is created.

#include<stdio.h>
main()
{
int id;
printf("Before fork()\n");
id=fork();

if(id==0)
{
printf("Child has started: %d\n ",getpid());
printf("Parent of this child : %d\n",getppid());
printf("child prints 1 item :\n ");
sleep(25);
printf("child prints 2 item :\n");
}
else
{
printf("Parent has started: %d\n",getpid());
printf("Parent of the parent proc : %d\n",getppid());
}

printf("After fork()");
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 23


LINUX PROGRAMMING LAB MANUAL

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

#include<unistd.h>

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main(int argc,char *argv[])

int fd[2],pid,k;

k=pipe(fd);

if(k==-1)

perror("pipe");

exit(1);

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 24


LINUX PROGRAMMING LAB MANUAL

pid=fork();

if(pid==0)

close(fd[0]);

dup2(fd[1],1);

close(fd[1]);

execlp(argv[1],argv[1],NULL);

perror("execl");

else

wait(2);

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 25


LINUX PROGRAMMING LAB MANUAL

close(fd[1]);

dup2(fd[0],0);

close(fd[0]);

execlp(argv[2],argv[2],NULL);

perror("execl");

Output:

cc prog19.c

./a.out ls sort

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 26


LINUX PROGRAMMING LAB MANUAL

20. Write C programs that illustrate communication between two unrelated processes
using named pipe.

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
int main()
{
int pfds[2];
char buf[30];
if(pipe(pfds)==-1)
{
perror("pipe");
exit(1);
}
printf("writing to file descriptor #%d\n", pfds[1]);
write(pfds[1],"test",5);
printf("reading from file descriptor #%d\n ", pfds[0]);
read(pfds[0],buf,5);
printf("read\"%s\"\n" ,buf);
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 27


LINUX PROGRAMMING LAB MANUAL

21. 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.

#include <stdio.h>
#include <sys/wait.h> /* contains prototype for wait */
#include<stdlib.h>
int main(void)
{
int pid;
int status;
printf("Hello World!\n");
pid = fork( );
if(pid == -1) /* check for error in fork */
{
perror("bad fork");
exit(1);
}
if (pid == 0)
printf("I am the child process.\n");
else
{
wait(&status); /* parent waits for child to finish */
printf("I am the parent process.\n");
}
}

Output:

$gcc prog21.c
$: ./a.out
Hello World!
I am the child process.
I am the parent process

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 28


LINUX PROGRAMMING LAB MANUAL

22. Write a C program to create a message queue with read and write permissions to write
3 messages to it with different priority numbers.

#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);
}
}
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 29


LINUX PROGRAMMING LAB MANUAL

$cc prog22.c
$ ./a.out

Enter the message to send

hi

Enter the message to send

hello

Enter the message to send

how

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 30


LINUX PROGRAMMING LAB MANUAL

23. Write a C program that receives the messages (from the above message queue as
specified in (22)) and displays them.

Aim: To create a message queue

#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);
}
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 31


LINUX PROGRAMMING LAB MANUAL

$ cc prog23.c
$ ./a.out

Message received from sender is hi

Message received from sender is welcome

Message received from sender is to

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 32


LINUX PROGRAMMING LAB MANUAL

24. Write a C program that illustrates suspending and resuming processes using signals.

#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;
}

Output:
Child loop
Child loop
Child loop
Child loop
Child loop
child.suspend()
Parent sleeps for 4 seconds
child.resume()
Child loop
Child loop
Child loop
Child loop
child.terminate()
Child loop
Parent finished

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 33


LINUX PROGRAMMING LAB MANUAL

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

Server.c

#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;
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 34


LINUX PROGRAMMING LAB MANUAL

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;
}

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;
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 35


LINUX PROGRAMMING LAB MANUAL

Client.c
#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);

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 36


LINUX PROGRAMMING LAB MANUAL

close(socket_fd);
return 0;
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 37


LINUX PROGRAMMING LAB MANUAL

26. Write client and server programs (using c) for interaction between server and client
processes using Internet Domain sockets.

Server.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

int main(int argc, char *argv[])


{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;

char sendBuff[1025];
time_t ticks;

listenfd = socket(AF_INET, SOCK_STREAM, 0);


memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

listen(listenfd, 10);

while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

ticks = time(NULL);
snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 38


LINUX PROGRAMMING LAB MANUAL

write(connfd, sendBuff, strlen(sendBuff));

close(connfd);
sleep(1);
}
}

Client.c

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])


{
int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;

if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}

memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}

memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 39


LINUX PROGRAMMING LAB MANUAL

serv_addr.sin_port = htons(5000);

if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)


{
printf("\n inet_pton error occured\n");
return 1;
}

if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)


{
printf("\n Error : Connect Failed \n");
return 1;
}

while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)


{
recvBuff[n] = 0;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
}

if(n < 0)
{
printf("\n Read error \n");
}

return 0;
}

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 40


LINUX PROGRAMMING LAB MANUAL

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

Source Code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<string.h>
#include<sys/shm.h>
#define shm_size 1024
int main(int argc,char * argv[])
{
key_t key;
int shmid;
char *data;
int mode;
if(argc>2)
{
fprintf(stderr,usage:stdemo[data_to_writte]\n);
exit(1);
}
if((shmid=shmget(key,shm_size,0644/ipc_creat))==-1)
{
perror(shmget);
exit(1);
}
data=shmat(shmid,(void *)0,0);
if(data==(char *)(-1))
{
perror(shmat);
exit(1);
}
if(argc==2)
printf(writing to segment:\%s\\n,data);
if(shmdt(data)==-1)
{
perror(shmdt);
exit(1);
}
return 0;
}
Input:

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 41


LINUX PROGRAMMING LAB MANUAL

#./a.out koteswararao
Output:
writing to segment koteswararao

KHADER MEMORIAL COLLEGE OF ENGG & TECHNOLOGY Page 42

You might also like