Professional Documents
Culture Documents
Linux Lab
Linux Lab
Linux Lab
LAB
OBJECTIVES:
OPERATING SYSTEMS
LINUX PROGRAMMING
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
man
The man command displays the manual page for the selected command.
Syntax: man<command-name>
Eg:man date
who
Eg:who
cat
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
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:
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
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().
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>
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().
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
Server:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
# define MAX 27
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
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
#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)
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++;
mutex=signal(mutex);
void consumer()
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
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).
#include <stdio.h>
#include <pthread.h>
printf("I am threadFunction.\n");
int main()
pthread_t id;
int ret;
/*creating thread*/
ret=pthread_create(&id,NULL,&threadFunction,NULL);
if(ret==0){
else{
return 0;
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'
------------------------------------------------------
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>
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;
}
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:
#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((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
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:
}
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 <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);
return 0;
}
server1.c:
return 0;
}
int main(void)
{
struct sockaddr_un address; int
socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
}
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;