Linux Lab

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

OPERATING SYSEMS AND LINUX PROGRAMMING

LAB

OBJECTIVES:

 To understand the design aspects of operating system.


 To study the process management concepts & Techniques.
 To study the storage management concepts.
 To familiarize students with theLinux environment
 To learn the fundamentals of shell scripting/programming
 To conceptualize Data Mining and the need for pre-processing.
 To learn the algorithms used for various types of Data Mining Problem

OPERATING SYSTEMS

1. Simulate the following CPU scheduling algorithms


a) Round Robin b) SJF c) FCFS d) Priority
2. Multiprogramming-Memory management- Implementation of fork (), wait (), exec() and
exit (), System calls
3. Simulate the following
a) Multiprogramming with a fixed number of tasks (MFT)
b) Multiprogramming with a variable number of tasks (MVT)
4. Simulate Bankers Algorithm for Dead Lock Avoidance
5. Simulate Bankers Algorithm for Dead Lock Prevention.
6. Simulate the following page replacement algorithms.
a) FIFO b) LRU c) LFU
7. Simulate the following File allocation strategies
a) Sequenced b) Indexed c) Linked

LINUX PROGRAMMING

1. a) Study of Unix/Linux general purpose utility command list


man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time, kill, history,
chmod, chown, finger, pwd, cal, logout, shutdown.
b) Study of vi editor.
c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
d) Study of Unix/Linux file system (tree structure).
e) Study of .bashrc, /etc/bashrc and Environment variables.
2.Write a C program that makes a copy of a file using standard I/O, and system calls
3. Write a C program to emulate the UNIX ls –l command.
4. Write a C program that illustrates how to execute two commands concurrently
with a command pipe.
Ex: - ls –l | sort
5. Write a C program that illustrates two processes communicating using sharedmemory
6. Write a C program to simulate producer and consumer problem usingsemaphores
7. Write C program to create a thread using pthreads library and let it run its function.
8. Write a C program to illustrate concurrent execution of threads using pthreads library.

OUTCOMES:

 To use Unix utilities and perform basic shell control of the utilities
 To use the Unix file system and file access control.
 To use of an operating system to develop software
 Students will be able to use Linux environment efficiently
 Solve problems using bash for shell scripting
 Will be able to implement algorithms to solve data mining problems using weka tool

BEYOND THE SYLLABUS:


1) Write a C program to create a message queue with read and write permissions to write 3
messages to it with different priority numbers.?
2) Write a C program that receives the messages(From the above message queue as specified in
(21) and display them.?
3) Write a C program that illustrates suspending and resuming processes using signals
4) Write client and server programs(using c) for interaction between server and client processes
using Unix Domain sockets
1.a)Study of UNIX/LINUX general purpose utility command list man ,who ,cat, cd, ps ,ls ,mv ,rm,
mkdir ,rmdir ,echo ,more ,date ,time ,kill, history,chmod,chown,finger,pwd,cal,logout,shutdown.

 man
The man command displays the manual page for the selected command.

Syntax: man<command-name>

Eg:man date

who

Displays who is on the system.

Syntax: who [option]

Eg:who

cat

View complete file content.

Syntax: cat <file_name>

Eg:cat linux

cd
changing the directory.
Syntax:cd <file_name>
Eg:
cd mydirectory
cd //go to home directory
cd .. //go to one directory
cp
copy files
cp[options] <source-filename> <destination_name>
Eg:cp linux unix
ps
Displays the active processes.
Syntax:ps
Eg:ps
ls
List the content of a directory.
Syntax:ls [options] <directory_path>
Eg:ls -l
mv
Move or rename files or directories.
Syntax:mv [options] <old_filepath> <new_filepath>
Eg:mv linux unix
rm
Remove files.
Syntax:rm [options] <file_name>
Eg:rm linux
mkdir
Create a new directory.
Syntax:mkdir <duirectory_path>
Eg:mkdir unix
rmdir
Remove a directory if it is empty.
Syntax:rmdir <directory_path>
Eg:rmdir unix
echo
Write a string to standard output.
Syntax:echo “string” or echo ‘string’
Eg:echo “LINUX”

more
View file contents in sections determined by the size of the terminal.
Syntax:more <file_name>
Eg:more
date
Displays today’s date.
Syntax:date [format]
Eg:date
time
Time a simple command or give resource usage.
Syntax:time [format] or time
Eg:time
kill
Terminate a process.
Syntax:kill [signal]
Eg:kill -9 pid
history
Manipulate history list.
Syntax:history
Eg:history
chmod
Change file mode bits.
Syntax:chmod 777 <file_name>
Eg:chmod 777 linux
chown
Change file owner and group.
Syntax:chown [owner] [group]

finger
Display information about local or remote users.
Syntax:finger <user_name>
finger <user_id>
Eg:finger madhu
pwd
Print name of current or working directory on the terminal.
Syntax:pwd [options]
Eg:pwd
cal
Display a calendar.
Syntax:cal [day] [month] [year]
Eg:cal 2017
logout
Write utmp and wtmp entries.
Syntax:logout
Eg:logout
shutdown
Halt,power-off or reboot the machine.
Syntax:shutdown [option]
Eg:shutdown

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

Aim: A C program that makes a copy of a file using standard I/O


#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
char a;
fp1=fopen("test","r");
if(fp1==NULL)
{
puts("cannot open this file");
exit(1);
}
fp2=fopen("test1","w");
if(fp2==NULL)
{
puts("not able to open this file");
fclose(fp1);
exit(1);
}
do
{
a=fgetc(fp1);
printf("the file characters %c \n",a);
fputc(a,fp2);
}while(a!=EOF);
printf("file copied sucessfully");
fcloseall();
exit(2);
}
OUTPUT:
Aim: Write a C program that makes a copy of a file using system calls

Sol: open(), read() and write() system calls

Lets continue with our first system call open() whose purpose is to open file for reading or writing or to
create new file.
You should open it's man page if you haven't already done so using man 2 open command and read trough
basics
(2 is manual section number, use man man to read more about integrated manual section numbers).
In the following example we also use read() and write() system calls to copy from one file descriptor to the
other
(both descriptors returned by open() system call) so it is wise to open their man pages as well (man 2 read
and man 2 write).
So here's the example code for program that copies input file passed as first argument into output file
passed as second argument:

Program:
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#define BUF_SIZE 8192
int main(int argc,char *argv[])
{
int input_fd,output_fd;
int ret_in,ret_out;
char buffer[BUF_SIZE];
if(argc!=3)
{
printf("Usage:cp file1 file2");
return 1;
}
input_fd=open(argv[1],O_RDONLY);
if(input_fd==-1)
{
perror("open");
return 2;
}
output_fd=open(argv[2],O_WRONLY | O_CREAT,0644);
if(output_fd==-1)
{
perror("open");
return 3;
}
while((ret_in=read(input_fd,&buffer,BUF_SIZE))>0)
{
ret_out=write(output_fd,&buffer,ret_in);
if(ret_out!=ret_in)
{
perror("write");
return 4;
}
}
printf("file is copied \n");
close(input_fd);
close(output_fd);
return(EXIT_SUCCESS);
}
Explanation:

If you have named this code file syscp.c and if you want to name executable file syscp to compile this
program
Then if your source file is named test and if you want to name the destination file test2
you would run this program like this:

./a.out test test2


Now lets go trough the code and explain tricky parts. First thing we must do is to include necessary header
files.
Man page of every system call tells you what header files you need to include to be able to use this system
call.
Second we will define constant we will use to define size of our buffer in bytes. Smaller buffer size will
make
our copy process longer but it will save memory. Next we open source and destination file descriptors,
source with O_RDONLY to
make it read only, destination with O_WRONLY | O_CREAT to make it writable and to create destination
file with 0644 file system
permission flags. In case of error we use perror() man 3 perror to print relatively user friendly error
message.

Now we are ready to start copy process. We run read() and write() inside loop (because source file might be
bigger than our buffer) to copy from one file into another. Important to notice is that write() is using number
of bytes read from source file returned by read() so it would know how much to write into destination file.
If number of bytes read (ret_in) and number of bytes written (ret_out) differ this indicates error so once
again we use perror() to print out error description. At the end if all went well we do cleanup by closing
both file descriptors and returning 0 (EXIT_SUCCESS) to indicate that program ended without errors.

OUTPUT:
3.Write a C program to emulate the linux ls –l command
Aim: A C program to emulate the linux ls –l command
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
int pid;
pid=fork();
if(pid<0)
{
printf("\nfork failed\n");
} exit(-1);
}
else if(pid==0)
{
execlp("/bin/ls","ls","-l",NULL);
}
wait(NULL);
printf("\nchild complete\n");
exit(0);
}

OUTPUT:

4. Write a C program that illustrates how to execute two commands concurrently with a command
pipe.

Eg:ls –l | sort
Aim: A C program that illustrates how to execute two commands concurrently with a command pipe.

#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int fd[2],pid,k;
k=pipe(fd);
if(k==-1)
{
perror("pipe");
return(1);
}
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);
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp(argv[2],argv[2],NULL);
perror("execl");
}
}
OUTPUT:

5.Write a c program that illustrates two processes communicating using shared memory

Aim: A c program that illustrates two processes communicating using shared memory

A process creates a shared memory segment using shmget().

The original owner of a shared memory segment can assign ownership to another user with shmctl().
It can also revoke this assignment.

Other processes with proper permission can perform various control functions on the shared memory
segment using shmctl().
Once created, a shared segment can be attached to a process address space using shmat().

It can be detached using shmdt() (see shmop()).


The attaching process must have the appropriate permissions for shmat().

Once attached, the process can read or write to the segment, as allowed by the permission requested in the
attach operation.
A shared segment can be attached multiple times by the same process.

A shared memory segment is described by a control structure with a unique ID that points to an area of
physical memory.
The identifier of the segment is called the shmid. The structure definition for the shared memory segment
control structures
andprototypews can be found in <sys/shm.h>.

A shared memory segment is identified by a unique integer, the shared memory ID.
The shared memory itself is described by a structure of type shmid_ds in header file sys/shm.h.
To use this file, files sys/types.h and sys/ipc.h must be included. Therefore, your program should
start with the following lines:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

A general scheme of using shared memory is the following:

For a server, it should be started before any client. The server should perform the following tasks:

1.Ask for a shared memory with a memory key and memorize the returned shared memory ID. This is
performed by system call shmget().
2.Attach this shared memory to the server's address space with system call shmat().
3.Initialize the shared memory, if necessary.
4.Do something and wait for all clients' completion.
5.Detach the shared memory with system call shmdt().
6.Remove the shared memory with system call shmctl().

For the client part, the procedure is almost the same:

1.Ask for a shared memory with the same memory key and memorize the returned shared memory ID.
2.Attach this shared memory to the client's address space.
3.Use the memory.
4.Detach all shared memory segments, if necessary.
5.Exit.
program:
-----------
We develop two programs here that illustrate the passing of a simple piece of memery
(a string) between the processes if running simulatenously:

shmserver.c -- simply creates the string and shared memory portion.


shmclient.c -- attaches itself to the created shared memory portion and uses the string

shmserver.c

Server:

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#include<stdio.h>

#include<stdlib.h>

# define MAX 27

void die(char *s)

perror(s);

exit(1);

int main()

char c;

int shmid;

key_t key;

char *shm,*s;

key=1224;

if((shmid=shmget(key,MAX,IPC_CREAT | 0666))<0)

die("shmget");
if((shm=shmat(shmid,NULL,0))==(char *) -1)

die("shmat");

s=shm;

for(c='a';c<='z';c++)

*s++=c;

while(*shm!='*')

sleep(1);

exit(0);

Output:

Client:

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#include<stdio.h>

#include<stdlib.h>

# define MAX 27

void die(char *s)


{

perror(s);

exit(1);

int main()

int shmid;

key_t key;

char *shm,*s;

key=1224;

if((shmid=shmget(key,MAX,0666))<0)

die("shmget");

if((shm=shmat(shmid,NULL,0))==(char *) -1)

die("shmat");

for(s=shm;*s!='\0';s++)

putchar(*s);

putchar('\n');

*shm='*';

exit(0);

Output:
6.Write a C program to simulate producer consumer problem using semaphore

Aim: A C program to simulate producer consumer problem using semaphore.

#include<stdio.h>

#include<stdlib.h>

int mutex=1,full=0,empty=5,x=0;

void producer();

void consumer();

int wait(int);

int signal(int);

void main()

int n;
printf("\n 1.Producer \n 2.Consumer \n 3.Exit");

while(1)

printf("\n Enter your choice:");

scanf("%d",&n);

switch(n)

case 1:

if((mutex==1)&&(empty!=0))

producer();

else

printf("Buffer is full");

break;

case 2:

if((mutex==1)&&(full!=0))

consumer();

else

printf("Buffer is empty");

break;

case 3:

exit(0);

break;

}
}

int wait(int s)

return (--s);

int signal(int s)

return(++s);

void producer()

mutex=wait(mutex);

full=signal(full);

empty=wait(empty);

x++;

printf("\n Producer produces the item %d",x);

mutex=signal(mutex);

void consumer()

mutex=wait(mutex);

full=wait(full);

empty=signal(empty);

printf("\n Consumer consumes item %d",x);

x--;
mutex=signal(mutex);

OUTPUT:

7.Write a C program to create a thread using pthreads library and let it run its function

Aim: A C program to create a thread using pthreads library and let it run its function
Sol:
Threads/ Processes are the mechanism by which you can run multiple code segments at a time, threads
appear to run concurrently;
the kernel schedules them asynchronously, interrupting each thread from time to time to give others chance
to execute.

We usually face the problem with threading program in C language in Linux. When we use pthread.h
library in our program,
program doesn't execute using simple (normal) compile command. After including pthread.h header file,
program doesn't compile
and return error(s).

Here is a program that will demonstrate example of threading.

#include <stdio.h>

#include <pthread.h>

/*thread function definition*/

void *threadFunction(void* args)

printf("I am threadFunction.\n");

int main()

/*creating thread id*/

pthread_t id;

int ret;

/*creating thread*/

ret=pthread_create(&id,NULL,&threadFunction,NULL);

if(ret==0){

printf("Thread created successfully.\n");


}

else{

printf("Thread not created.\n");

return 0; /*return from main*/

printf("I am main function.\n");

return 0;

The compile command is:

cc thread.c -o thread
program will throw an error, and the error is:

partial output:
------------------------------------------------------
sh-4.3$ gccthread.c -o thread
thread.c: undefined reference to 'pthread_create'
------------------------------------------------------

Then, how to compile C program with pthread.h library?

To compile C program with pthread.h library,


you have to put -lpthread just after the compile command gccthread.c -o thread.
This command will tell to the compiler to execute program with pthread.h library.

The command is:

gccthread.c -o thread -lpthread

>gcc is the compiler command.


>thread.c is the name of c program source file.
> -o is option to make object file.
> thread is the name of object file.
> -lpthread is option to execute pthread.h library file.

See the output after running this command

OUTPUT:
8. Write a C program to illustrate concurrent execution of threads using pthreads library.
Aim: A C program to illustrate concurrent execution of threads using pthreads library.

Sol:Thread Creation
Normally when a program starts up and becomes a process, it starts with a default thread. So we can say
that every process has at least one thread of control.  A process can create extra threads using the following
function :

#include <pthread.h>

int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void
*restrict arg)

The above function requires four arguments, lets first discuss a bit on them :

 The first argument is a pthread_t type address. Once the function is called successfully, the variable
whose address is passed as first argument will hold the thread ID of the newly created thread.
 The second argument may contain certain attributes which we want the new thread to contain.  It
could be priority etc.
 The third argument is a function pointer. This is something to keep in mind that each thread starts
with a function and that functions address is passed here as the third argument so that the kernel knows
which function to start the thread from.
 As the function (whose address is passed in the third argument above) may accept some arguments
also so we can pass these arguments in form of a pointer to a void type. Now, why a void type was
chosen? This was because if a function accepts more than one argument then this pointer could be a
pointer to a structure that may contain these arguments.

Thread join
 which is the thread in which main() function is executed. So maximum lifetime of every thread
executing in the program is that of the main thread. So, if we want that the main thread should wait
until all the other threads are finished then there is a function pthread_join().
 #include <pthread.h>
 int pthread_join(pthread_t thread, void **rval_ptr);
 The function above makes sure that its parent thread does not terminate until it is done. This
function is called from within the parent thread and the first argument is the thread ID of the thread
to wait on and the second argument is the return value of the thread on which we want to the parent
thread to wait. If we are not interested in the return value then we can set this pointer to be NULL.

#include <stdio.h>
#include <pthread.h>

void do_one_thing(int *);


void do_another_thing(int *);
void do_wrap_up(int, int);

int r1 = 0, r2 = 0;

int main(void)
{
pthread_t thread1, thread2;
pthread_create(&thread1,NULL,(void *) do_one_thing,(void *) &r1);
pthread_create(&thread2,NULL,(void *) do_another_thing,(void *) &r2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
do_wrap_up(r1, r2);
return 0;
}

void do_one_thing(int *pnum_times)


{
int i, j, x;
for (i = 0; i < 4; i++)
{
printf("doing one thing\n");
for (j = 0; j < 10000; j++)
x = x + i;
(*pnum_times)++;
}
}

void do_another_thing(int *pnum_times)


{
int i, j, x;
for (i = 0; i < 4; i++)
{
printf("doing another \n");
for (j = 0; j < 10000; j++)
x = x + i;
(*pnum_times)++;
}
}

void do_wrap_up(int one_times, int another_times)


{
int total;
total = one_times + another_times;
printf("wrap up: one thing %d, another %d, total %d\n", one_times, another_times, total);
printf("\n Fianlly the Concurrent execution of pthreads is done successfully");
}

OUTPUT:

BEYOND SYLLABUS:

AIM :20. Write a C program to create a message queue with read and write permissions to
write 3 messages to it with different priority numbers.?
THEORY:

Msgget():The msgget function can be used to create the message queue.


Msgrcv():The msgrcv function can be used to receive the messages.
Msgsnd():The msgsnd function can be used to send the messages to another process.

#include <stdio.h>
#include <sys/ipc.h>
#include <fcntl.h>
#define MAX 255
struct mesg
{
long type;
char mtext[MAX];
} *mesg;
char buff[MAX];
main()
{
int mid,fd,n,count=0;;
if((mid=msgget(1006,IPC_CREAT | 0666))<0)

{
printf(“\n Can‟t create Message Q”);
exit(1);

}
printf(“\n Queue id:%d”, mid);
mesg=(struct mesg *)malloc(sizeof(struct mesg));
mesg ->type=6;

fd=open(“fact”,O_RDONLY);
while(read(fd,buff,25)>0)
{
strcpy(mesg ->mtext,buff);

if(msgsnd(mid,mesg,strlen(mesg ->mtext),0)== -1)


printf(“\n Message Write Error”);
}

if((mid=msgget(1006,0))<0)
{
printf(“\n Can‟t create Message Q”);
exit(1);
}
while((n=msgrcv(mid,&mesg,MAX,6,IPC_NOWAIT))>0)
write(1,mesg.mtext,n);

count ;
if((n= = -1)&(count= =0))
printf(“\n No Message Queue on Queue:%d”,mid);

AIM: Write a C program that receives the messages(From the above message queue as specified
in (21) and display them.?

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MSGSZ 128

* Declare the message structure. */


typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid; key_t
key;

message_buf rbuf;
/*
* Get the message queue id for the
* "name" 1234, which was created by
* the server.
*/
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
{ perror("msgget");
exit(1);
}
/*
* Receive an answer of message type 1.
*/
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
/*
* Print the answer.
*/
printf("%s\n", rbuf.mtext);
exit(0);
}

Execution Steps:
[student@gcet ~]$cc message_send.c
[student@gcet ~]$ mv a.out msgsend
[student@gcet ~]$ ./msgsend

msgget: Calling msgget(0x4d2,01666) msgget: msgget succeeded: msqid = 0 msgget: msgget succeeded:
msqid = 0 msgget: msgget succeeded: msqid = 0 Message: "Did you get this?" Sent [student@gcet ~]
$ cc message_rec.c [student@gcet ~]$ mv a.out msgrec [student@gcet ~]$./msgrec

AIM: Write a C program that illustrates suspending and resuming processes using signals?
THEORY:

Signal : The signal can be used to send a events to the processes.


Socket: The socket can be used to create the communication on end points.
Port number: The port number can be used to identify the individual process on sytem.

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

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

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

server1.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;

You might also like