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

Linux Lab

This document provides code snippets for various Linux programming lab exercises: 1. A shell script that displays lines between given line numbers in a file. 2. A shell script that deletes lines containing a specified word from one or more files. 3. A shell script that lists files with read, write and execute permissions in the current directory. It also includes C programs and awk scripts for tasks like copying files, emulating Unix commands like cat, ls and mv, finding number of lines/words in a file, and more Linux programming related exercises.

Uploaded by

ZainaZaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Linux Lab

This document provides code snippets for various Linux programming lab exercises: 1. A shell script that displays lines between given line numbers in a file. 2. A shell script that deletes lines containing a specified word from one or more files. 3. A shell script that lists files with read, write and execute permissions in the current directory. It also includes C programs and awk scripts for tasks like copying files, emulating Unix commands like cat, ls and mv, finding number of lines/words in a file, and more Linux programming related exercises.

Uploaded by

ZainaZaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

LINUX

PROGRAMMING
LAB MANUL
1)Write a shell script that accepts a filename , starting and ending line number as
arguments and display all the lines between the given line numbers

SHELLSCRIPT : $vi f1.sh

echo "enter file name"


read file
echo "starting line no"
read s
echo "ending line no"
read n
echo " the line between $s and $n"
sed -n $s,$n\p $file|cat>newline
cat newline

input: $vi f1.txt


first
second
third
four

output: $ sh f1.sh
enter file name
f1.txt
starting line no
2
Ending line no
3
the line between 2 and 3
second
third
2) Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.

Shell script: $vi f2.sh

echo "enter word to search and delete"


read word
echo "the files to be searched are $*"
for i in $*
do
echo "filename:$i"
grep -v $word $i
done

output: $sh f2.sh f1.txt


enter word to search and delete
third
the files to be searched are file1.txt
filename:file1.txt
first
second
four
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.

Shell script: $vi f3.sh

echo “list of files which have read,write and execute permissions in a current
directory”
for file in *
do
if [ -r $file –a –w $file –a –x $file ]
then
echo “$file”
fi
done

input:
$chmod a+rwx f1.txt
$chmod a+rwx f1.sh
$chmod a+rwx f2.sh

output: $sh f3.sh


list of files which have read,write and execute permissions in a current directory
f1.txt
f2.sh
f1.sh
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

Shell script: $vi f4.sh

echo "the files are $*"


for i in $*
do
echo "file name is : $i"
echo "No of lines are :"
wc -l $i
done

input:
$vi f1.txt
first
second
third

$vi f2.txt
four
five
six
seven

output: $sh f4.sh f1.txt f2.txt


the files are f1.txt f2.txt
file name are : f1.txt
No of lines is :
3 f1.txt
file name is : f2.txt
No of lines are :
4 f2.txt
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 files.

Shell script: $vi f5.sh


echo "the files are $*"
for i in $*
do
echo "file name is : $i"
echo "No of words are :"
wc -w $i
done

output:$sh f5.sh f1.txt f2.txt


the files are f1.txt f2.txt
file name are : f1.txt
No of words is :
3 f1.txt
file name is : f2.txt
No of words are :
4 f2.txt
6) Write a shell script to list all of the directory files in a directory.

Shell script: $vi f6.sh

echo “enter dir name”


read dir
echo “files in $dir are”
ls $dir

input :
$mkdir cse
$cd cse
$vi a.txt
$vi b.txt

Output: $sh f6.sh


enter dir name
cse
files in cse are
a.txt b.txt f6.sh
7) Write a shell script to find factorial of a given integer.
Shell script: $vi f7.sh
echo "enter the number"
read n
fact=1
echo "factorial of $n"
while(($n>0))
do
((fact= $fact*$n))
((n=$n-1))
done
echo "is $fact"

output: $ sh f7.sh
enter the number
5
factorial of 5
is 120
8) Write an awk script to count the number of lines in a file that do not contain vowels.

AWKScript: $vi f8.awk

BEGIN{
printf " the no of lines not contain vowels are "
}!/[aA]|[eE]|[iI]|[oO]|[uU]/{
k++
}
END{
printf "%d \n",k
}

input : $vi list.txt


sky
shy
fly
cat
bat

output: $ awk -f f8.awk list.txt


the no of lines not contain vowels are 3
9) Write an awk script to find the number of characters, words and lines in a file.
AWK script: $vi f9.awk
BEGIN { printf "l \t c\t w\n"}
#BODY section
{
len=length($0)
total_len+=len
print(NR,"\t",len,"\t",NF,$o)
words+=NF
}
END{
print("\n total")
print("words:\t" words)
print("characters:\t" total_len)
print("lines \t" NR)
}

Output: $awk -f f9.awk f1.txt


l c w
1 5 1 first
2 6 1 second
3 5 1 third
4 0 0

total
words: 3
characters: 16
lines 4
10 Write a c program that makes a copy of a file using standard I/O and system calls

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{

FILE *fds,*fdd;
char ch;
fds = fopen(argv[1], "r");
fdd = fopen(argv[2], "w");
while(!feof (fds))

putc(getc(fds),fdd);
fclose(fds);
fclose(fdd);
}
Output

$ vi f10.c
$ cc f10.c
$ ./a.out f1.txt f2.txt
11 Implement in C the following UNIX commands using System calls
A. cat B. ls C. mv

a cat
#include<stdio.h>
#include<stdlib.h>
main(int argc, char *argv[])
{

FILE *fp;
int i;
for(i=1;i<argc;i++)
{
fp = fopen (argv[i], "r");

while (!feof(fp))
putc(getc(fp),stdout);
fclose(fp);
}
}

Output

$ vi f11a.c
$ cc f11a.c
$ ./a.out xyz.txt
linux

programming
11 b ls
#include<stdio.h>

#include<string.h>
#include<dirent.h>
#include<stdlib.h>
#include<sys/types.h>
int main(int argc ,char **argv)
{
DIR *dp;
struct dirent *dirp;
char p[8];
if(argc==1)

strcpy(p,".");
else
{
strcpy(p,argv[1]);
}

if((dp=opendir(p))==NULL)
{
printf("can't open directoey");
exit(0);
}
while((dirp=readdir(dp))!=NULL)

{
printf("%s\n",dirp->d_name);
}
closedir(dp);
return 1;
}

Output

$ vi f11b.c
$ cc f11b.c
$ ./a.out
f2.txt
a.out
f11a.c
xyz.txt
f11b.c

f10.c
f1.txt
f11c.c
11 c mv
#include<stdio.h>

#include<stdlib.h>
int main(int argc, char *argv[])
{
FILE *fps,*fpd;
fps = fopen(argv[1], "r");
fpd = fopen(argv[2], "w");
while (!feof(fps))
putc(getc(fps),fpd);
fclose(fpd);
}

Output

$ vi f11c.c
$ cc f11c.c
$ ./a.out f1.txt f2.txt
12. Write a program that takes one or more file/directory names as command line input and
reports the following information on the file.
A. File type. B. Number of links.
C. Time of last access. D. Read, Write and Execute permissions.

for i in $*

do

if [ -d $i ]

then

echo "Given directory name is found as $i"

fi

if [ -f $i ]

then

echo "Given name is a file as $i "

fi

echo "Type of file/directory $i"

file $i

echo "Last access time is:"

ls -l $i

echo "no.of links"

ln $i

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

then

echo "$i contains all permission"

else

echo "$i does not contain all permissions"

fi
done

output

[meher@localhost cprog]$ vi f12.sh

[meher@localhost cprog]$ sh f12.sh xyz.txt

Given name is a file as xyz.txt

Type of file/directory xyz.txt

xyz.txt: Pascal source, ASCII text

Last access time is:

-rwxrwxrwx. 3 meher meher 18 Sep 2 09:00 xyz.txt

no.of links

ln: failed to create hard link â./xyz.txtâ: File exists

xyz.txt contains all permission

Given name is a file as xyz.txt

Type of file/directory xyz.txt

xyz.txt: Pascal source, ASCII text

Last access time is:

-rwxrwxrwx. 3 meher meher 18 Sep 2 09:00 xyz.txt

no.of links

ln: failed to create hard link â./xyz.txtâ: File exists

xyz.txt contains all permission

[meher@localhost cprog]$
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);
}

Output

[meher@localhost cprog]$ vi f13.c

[meher@localhost cprog]$ cc f13.c

[meher@localhost cprog]$ ./a.out

total 96

drwxrwxr-x. 2 meher meher 4096 Jul 29 10:47 abc

-rwxrwxr-x. 1 meher meher 8751 Sep 2 09:19 a.out

-rw-rw-r--. 1 meher meher 0 Jul 29 10:46 a.txt

-rw-rw-r--. 1 meher meher 0 Jul 29 10:46 b.txt

-rw-rw-r--. 1 meher meher 221 Jul 31 11:24 f10.c

-rw-rw-r--. 1 meher meher 192 Jul 31 11:26 f11a.c


14 Write a C program to list for every file in a directory, its inode number and file name.
#include<stdio.h>
#include<sys/stat.h>

#include<unistd.h>
#include<stdlib.h>
#include<dirent.h>
int main(int argc,char **argv)
{
DIR *dp;
struct stat buf;
ino_t ino;
struct dirent *dirp;
if(argc!=2)

{
printf("usage:dirname");
exit(1);
}
if((dp=opendir(argv[1]))==NULL)

perror("open:");
printf("\n inode filename");
printf("\n----------------");
while((dirp=readdir(dp))!=NULL)
{
stat(dirp->d_name,&buf);

ino=buf.st_ino;
printf("\n %ld %s",ino,dirp->d_name);
}
return 1;
}
Output

$ vi f14.c
$ cc f14.c
$ ./a.out abc

inode filename
----------------
131123 .
131170 b.txt
131080 ..
131169 a.txt
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

[meher@localhost cprog]$ vi lsf1.c

[meher@localhost cprog]$ cc lsf1.c


[meher@localhost cprog]$ ls

abc f1 f11c.c f14.c f18.c lsf1.c PID:3452 xyz.txt

a.out f10.c f12.c f15.c f1.txt lssort.c PPID:3451 zombie.c

a.txt f11a.c f12.sh f16.c f2 orphan.c pqr.txt

b.txt f11b.c f13.c f17.c f2.txt PID:3451 p.txt

[meher@localhost cprog]$ cat > f1

^z

^C

[meher@localhost cprog]$ ./a.out f1

[meher@localhost cprog]$ cat f1

abc

a.out

a.txt

b.txt

f1

f10.c

f11a.c

f11b.c

f11c.c

f12.c

f12.sh

f13.c

f14.c

f15.c

f16.c
f17.c

f18.c

f1.txt

f2

f2.txt

lsf1.c

lssort.c

orphan.c

PID:3451

PID:3452

PPID:3451

pqr.txt

p.txt

xyz.txt

zombie.c
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>

main ()
{
int childpid;
childpid = fork();
if(childpid==0)

printf(" child process\n");


else
printf("\n parent process");
}
Output
$ vi f16.c

$ cc f16.c
$ ./a.out
child process
parent process
17 Write a C program to create a Zombie process.

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int id ,x ,y;
id=fork();
if(id==0)
{

x=getpid();
y=getppid();
printf("Child process 1>PID:%d \n2>PPID:%d",x,y);
sleep(5);
printf("\nchild terminated");

}
else{
x=getpid();
y=getppid();
printf("Parent process 1>PID:%d \n2>PPID:%d",x,y);
sleep(20);

wait(&id);
printf("parent terminated");
}
return(0);
}
Output

$ vi zombie.c
$ cc zombie.c
$ ./a.out
Parent process 1>PID:3419
Child process 1>PID:3420
2>PPID:3419
child terminated2>PPID:3321parent terminated
18 Write a C program that illustrates how an orphan is created.
#include<stdio.h>

main()
{
int id;
id=fork();
if(id==0)
{
printf("Child has started: %d\n ",getpid());
printf("Parent of this child : %d\n",getppid());
sleep(10);
printf("child");

}
else {
printf("Parent has started: %d\n",getpid());
printf("Parent of the parent proc : %d\n",getppid());
}

printf("child is alive and parent is dead");


}
Output
$ vi orphan.c
$ cc orphan.c
$ ./a.out

Parent has started: 3428


Child has started: 3429
Parent of the parent proc : 3321
Parent of this child : 3428

child is alive and parent is dead child child is alive and parent is dead
19. Write a C program that illustrates how to execute two commands concurrently with a
command pipe.
Ex: - ls –l | sort

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <stdlib.h>

int main()

int pfds[2];

char buf[30];

if(pipe(pfds)==-1)

perror("pipe failed");

exit(1);

if(!fork())

close(1);

dup(pfds[1]);

system ("ls -l");

else

printf("parent reading from pipe \n");


while(read(pfds[0],buf,80))

printf("%s \n" ,buf);

Output

[meher@localhost cprog]$ cc lssort.c

[meher@localhost cprog]$ ./a.out

drwxrwxr-x. 2 meher meher 4096 Jul 29 10:47 abc

-rwxrwxr-x. 1 meher meh

total 92

drwxrwxr-x. 2 meher meher 4096 Jul 29 10:47


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

#include<stdio.h>

#include<stdlib.h>

#include<errno.h>

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

}
Output

[meher@localhost cprog]$ vi f20.c

[meher@localhost cprog]$ cc f20.c

[meher@localhost cprog]$ ./a.out

writing to file descriptor #4

reading from file descriptor #3

read"test"

[meher@localhost cprog]$
21 Write a C program to create a message queue with read and write permissions to write 3
messages to it with different priority numbers.
Program:

#include<stdio.h>

#include<string.h>

#include<sys/ipc.h>

#include<sys/msg.h>

struct msgbuf

long mtype;

char mtext[50];

mobj={15,"HELLO"};

int main()

int fd=msgget(150,IPC_CREAT| IPC_EXCL|0642);

if(fd==-1||msgsnd(fd,&mobj,strlen(mobj.mtext)+1,IPC_NOWAIT))

perror("message error");

return 0;

Output:

$ vi mq.c

$ cc mq.c
$ ipcs

------ Message Queues --------

key msqid owner perms used-bytes messages

0x00000096 0 meher 642 6 1

------ Shared Memory Segments --------

key shmid owner perms bytes nattch status

------ Semaphore Arrays --------

key semid owner perms nsems


22 Write a C program that receives the messages(From the above message queue as specified in
(21) and display them.
Program: #include<stdio.h>

#include<string.h>
#include<sys/ipc.h>
#include<sys/msg.h>
struct msgbuf
{

long mtype;
char mtext[50];
}
mobj={15,”HELLO”};
main()

{
int fd;
fd=msgget(100,IPC_CREAT|IPC_EXCL|0642);
if(msgrcv(fd,&mobj,50,20,MSG_NOERROR)>0)
printf(“\n %5s \n”,mobj.mtext);

else
printf(“\n message receive error \n “);
return 0;
}
output:
$vi mqr.c

$cc mqr.c
$ipcs
------ Message Queues --------

key msqid owner perms used-bytes messages

0x00000096 0 meher 642 6 1

------ Shared Memory Segments --------

key shmid owner perms bytes nattch status

------ Semaphore Arrays --------

key semid owner perms nsems


23 Write a C Program to allow cooperating processes to lock a resource for exclusive use,using
a)Semaphores,b)Flock or lockf system calls
Program:

#include<stdio.h>

#include<stdlib.h>

#include<error.h>

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/sem.h>

int main(void)

key_t key;

int semid;

if((key==ftok("s.txt","j"))==-1)

perror("ftok");

exit(1);

if((semid=semget(key,1,IPC_CREAT|0666))==-1)

perror("semget");

exit(1);

if(semctl(semid,0,SETVAL,0)==-1)
{

perror("smctl");

exit(1);

return 0;

Output:

$vi 23.c

$cc 23.c

[meher@localhost cprog]$ ipcs

------ Message Queues --------

key msqid owner perms used-bytes messages

0x00000096 0 meher 642 6 1

0x00000064 32769 meher 642 0 0

------ Shared Memory Segments --------

key shmid owner perms bytes nattch status

0x00000000 294915 swcet 600 2097152 2 dest

------ Semaphore Arrays --------

key semid owner perms nsems

0x00000000 0 meher 600 1


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

#include<sys/types.h>
#include<signal.h>
//suspend the process(same as hitting crtl+z)
kill(pid,SIGSTOP);

//continue the process


kill(pid,SIGCONT);
25 Write a C program that implements a producer-consumer system with two processes.(Using
Semaphores).
Program:

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<time.h>

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/sem.h>

#define NUM_LOOPS 20

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

int semid;

int child_pid;

int i;

struct sembuf sem_op;

int rc;

struct timespec delay;

semid=semget(IPC_PRIVATE,1,0600);

if(semid==-1)

perror("main:semget");

exit(1);
}

printf("semaphores set created, semaphore set id '%d' \n",semid);

rc =semctl(semid,0,SETVAL,0);

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;

semop(semid,&sem_op,1);

printf("consumer:'%d' \n", i);

fflush(stdout);

sleep(3);

break;

default:

for(i=0;i<NUM_LOOPS;i++)
{

printf("producer:%d\n",i);

fflush(stdout);

sem_op.sem_num=0;

sem_op.sem_op=1;

sem_op.sem_flg=0;

semop(semid,&sem_op,1);

sleep(2);

if(rand( )>3*(RAND_MAX/4))

delay.tv_sec=0;

delay.tv_nsec=10;

nanosleep(&delay,NULL);

break;

return 0;

Output: [meher@localhost cprog]$ vi 25.c

[meher@localhost cprog]$ cc 25.c

[meher@localhost cprog]$ ./a.out

semaphores set created, semaphore set id '0'


producer:0

consumer:'0'

producer:1

consumer:'1'

producer:2

consumer:'2'

producer:3

producer:4

consumer:'3'

producer:5

consumer:'4'

producer:6

producer:7

consumer:'5'

producer:8

consumer:'6'

producer:9

producer:10

consumer:'7'

producer:11

consumer:'8'

producer:12
26. 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;
}

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

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

close(socket_fd);
return 0;
}
27. 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));
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;
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;
}
28 Write a C program that illustrates inter process communication using shared memory.
Program:
#include<stdio.h>
#include<string.h>

#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>

#include<sys/types.h>
#define SEGSIZE 100
int main(int argc,char *argv[])
{
int shmid,cntr;

key_t key;
char *segptr;
char buff[]=”hello world”;
key=ftok(“.”,’s’);
if((shmid=shmget(key,SEGSIZE,IPC_CREAT|IPC_EXCL|0666))==-1)

{
if((shmid=shmget(key,SEGSIZE,0))==-1)
{
perror(“shmget”);
exit(1);
}

}
else
{
printf(“ creating a new shared memory seg \n “);
printf(“SHMID:%d”,shmid);
}

system(“ipcs -m”);
if((segptr=shmat(shmid,0,0))==(char*)-1)
{
perror(“shmat”);
exit(1);
}
printf(“writing data to shared memory…\n “);
strcpy(segptr,buff);
printf(“DONE \n”);
printf(“reading data from shared memory…\n”);

printf(“ DATA:-%s \n”,segptr);


printf(“DONE \n”);
printf(“removing shared memory segment…\n”);
if(shmctl(shmid,IPC_RMID,0) = = -1)
printf(“cant’t remove shared memory segment…\n “);

printf(“removed successfully”);
}

Output

$vi 28.c

$cc 28.c

$ ./a.out

creating a new shared memory seg


------ Shared Memory Segments --------

key shmid owner perms bytes nattch status

0xd0060033 0 meher 666 100 0

SHMID:0writing data to shared memory.

DONE

reading data from shared memory.

DATA:-hello world

DONE

removing shared memory segment.

removed successfully[

You might also like