study - WordPress.com

advertisement
1
I.
AIM :-TO Write C programs that uses open, read, write system calls.
PROGRAM :#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);
}
// Case of an error exit from the loop
if(n1 == -1)
{
perror("Reading problem ");
exit(2);
}
close(fd2);
exit(0);
}
OUTPUT :-
2
II.
AIM :- Simple C program that demonstrates the failure of fork system call because of
crossing system limits.
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
pid_t pid;
int x = 5;
pid =
fork(); x++;
if (pid < 0)
{
printf("Process creation
error"); exit(-1);
}
else
if (pid == 0)
{
printf("Child process:");
printf("\nProcess id is %d", getpid());
printf("\nValue of x is %d", x);
printf("\nProcess id of parent is %d\n", getppid());
}
else
{
printf("\nParent process:");
printf("\nProcess id is %d", getpid());
printf("\nValue of x is %d", x);
printf("\nProcess id of shell is %d\n", getppid());
}
}
OUTPUT :
$ gcc fork.c
$ ./a.out
Child process:Process id is 19499
Value of x is 6
Process id of parent is 19498
Parent process: Process id is 19498
Value of x is 6 Process id of shell is 3266
3
III.
AIM : TO Simple C programs to illustrate the use of exec family of functions.
PROGRAM :
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
main(int argc, char*argv[])
{
pid_t pid;
int i;
if (argc != 3)
{
printf("\nInsufficient arguments to load program");
printf("\nUsage: ./a.out <path> <cmd>\n"); exit(1);
}
switch(pid = fork())
{
case -1:
printf("Fork
failed"); exit(-1);
case 0:
printf("Child process\n");
i = execl(argv[1], argv[2],0);
if (i < 0)
{
printf("%s program not loaded using exec system call\n", argv[2]);
exit(-1);
}
default:
wait(NULL);
printf("Child Terminated\n"); exit(0);
}
}
OUTPUT :
4
IV.
AIM : Write C programs that differentiates FILE *( file stream pointers in C
standard library) and file descriptors by using functions such as fdopen, fileno.
PROGRAM :
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main()
{
int fd;
FILE *fp;
fd = open("test.txt",O_WRONLY | O_CREAT | O_TRUNC);
if( fd < 0 ){
printf("open call fail");
return -1;
}
fp=fdopen(fd,"w");
printf("we got file pointer fp bu using File descriptor fd");
fclose(fp);
return 0;
}
OUTPUT :
5
V.
AIM : Write a C program which displays a given files meta data by using stat
system call and st_mode structure.
PROGRAM :
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
if(argc != 2)
return 1;
struct stat fileStat;
if(stat(argv[1],&fileStat) < 0)
return 1;
printf("Information for %s\n",argv[1]);
printf("---------------------------\n");
printf("File Size: \t\t%d bytes\n",fileStat.st_size);
printf("Number of Links: \t%d\n",fileStat.st_nlink);
printf("File inode: \t\t%d\n",fileStat.st_ino);
printf("File Permissions: \t");
printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");
printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n\n");
printf("The file %s a symbolic link\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");
return 0;
}
OUTPUT :
6
VI.
AIM : Write a C program which lists all the files of current working directory
whose size is more than given number of data blocks.
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char buf[4096];
int main()
{
char *cwd = getcwd(buf, sizeof(buf));
if (!cwd) {
perror("getcwd");
exit(1);
}
printf("%s\n", cwd);
return 0;
}
OUTPUT :
7
VII.
AIM : Write a C program which lists all the files of current working directory
which contains hard link files.
PROGRAM :
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
Int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
puts ("Couldn't open the directory.");
return 0;
}
OUTPUT :
8
VIII.
AIM : Simple C programs to demonstrate the use of pipe system call for inter
process communication and alsoemulating piping in shell.
PROGRAM :
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MSGLEN 64
int main()
{
int fd[2];
pid_t pid;
int result;
//Creating a pipe
result = pipe (fd);
if (result < 0)
{
//failure in creating a pipe
perror("pipe");
exit (1);
}
//Creating a child process
pid = fork();
if (pid < 0) {
//failure in creating a child
perror ("fork");
exit(2);
}
if (pid == 0) {
//Child process
char message[MSGLEN];
while(1) {
//Clearing the message
memset (message, 0, sizeof(message));
printf ("Enter a message: ");
scanf ("%s",message);
//Writing message to the pipe
9
write(fd[1], message, strlen(message));
}
exit (0);
}
else {
//Parent Process
char message[MSGLEN];
while (1) {
//Clearing the message buffer
memset (message, 0, sizeof(message));
//Reading message from the pipe
read (fd[0], message, sizeof(message));
printf("Message entered %s\n",message);
}
exit(0);
}
}
OUTPUT :
10
IX.
AIM : Write a C program to illustrate inter process communication via shared
memory.
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27
main()
{
char c;
int shmid;
key_t key = 2013;
char *shm, *s;
if ((shmid = shmget(key, shmsize, IPC_CREAT|0666)) < 0)
{
perror("shmget");
exit(1);
}
printf("Shared memory id : %d\n", shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
memset(shm, 0,
shmsize); s = shm;
printf("Writing (a-z) onto shared
memory\n"); for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = '\0';
while (*shm != '*');
printf("Client finished reading\n");
if(shmdt(shm) != 0)
fprintf(stderr, "Could not close memory segment.\n");
shmctl(shmid, IPC_RMID, 0);
}
11
OUTPUT :
12
X.
AIM:-TO WITE A PROGRAM TO CREATE MESSAGE WITH 3 DIFFERENT NUMBERS
OF PRIORTY NUMBERS.
PROGRAM :#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++;
13
if((n= = -1)&(count= =0))
printf(“\n No Message Queue on Queue:%d”,mid);
}
OUTPUT :-
14
XI.
AIM :- Write a Program to implement Remote Command Execution.
PROGRAM :#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv){
int x, z;
char *host_ip = "127.0.0.1";
short host_port = 1234;
char *remote_ip = "127.0.0.1";
short remote_port = 1235;
int host_sock, remote_sock;
char datagram[512];
char path[1024]={0};
int remote_len;
FILE *fp; /* it will open a stream for the output of command */
struct sockaddr_in host_add;
struct sockaddr_in remote_add
host_sock = socket(AF_INET, SOCK_DGRAM, 0);
host_add.sin_family = AF_INET;
host_add.sin_port = htons(host_port);
host_add.sin_addr.s_addr = inet_addr(host_ip);
z = bind(host_sock, (struct sockaddr *)&host_add, sizeof(host_add));
while(1)
{
puts("Waiting for command.........");
bzero(datagram, 512);
z = recvfrom(host_sock, datagram, 512, 0, (struct sockaddr*)&remote_add, &remote_len);
datagram[z] = 0;
printf("Command:%s", datagram);
fp = popen(datagram, "r");
bzero(datagram, sizeof(datagram));
remote_sock = socket(AF_INET, SOCK_DGRAM, 0);
remote_add.sin_family = AF_INET;
15
remote_add.sin_port = htons(remote_port);
remote_add.sin_addr.s_addr = inet_addr(remote_ip);
while(fgets(datagram, sizeof(datagram)-1, fp) != NULL){
x = sendto(remote_sock, datagram, strlen(datagram), 0, (struct sockaddr *)&remote_add, sizeof(remote_add));
bzero(datagram, sizeof(datagram));
}
strcpy(datagram, "___EOF___");
x = sendto(remote_sock, datagram, strlen(datagram), 0, (struct sockaddr *)&remote_add, sizeof(remote_add));
close(remote_sock);
}
close(host_sock);
return 0;
}
OUTPUT :-
16
XII.
AIM :- Create a Socket (TCP) between two computers and enable file transfer
between them .
PROGRAM :#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(void)
{
int sockfd = 0;
int bytesReceived = 0;
char recvBuff[256];
memset(recvBuff, '0', sizeof(recvBuff));
struct sockaddr_in serv_addr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000); // port
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
FILE *fp;
fp = fopen("sample_file.txt", "ab");
if(NULL == fp)
{
printf("Error opening file");
return 1;
17
}
while((bytesReceived = read(sockfd, recvBuff, 256)) > 0)
{
printf("Bytes received %d\n",bytesReceived);
// recvBuff[n] = 0;
fwrite(recvBuff, 1,bytesReceived,fp);
// printf("%s \n", recvBuff);
}
if(bytesReceived < 0)
{
printf("\n Read Error \n");
}
return 0;
}
OUTPUT :-
18
XIII.
AIM :- Write socket Programs in C for Echo/Ping/Talk Commands.
PROGRAM:#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define SOCK_PATH "echo_socket"
int main(void)
{
int s1,t,len;
struct sockaddr_un remote;
char str[100];
if((s1=socket(AF_UNIX,SOCK_STREAM,0))==-1)
{
printf("socket\n");
exit(1);
}
printf("Trying to connect\n");
remote.sun_family=AF_UNIX;
strcpy(remote.sun_path,SOCK_PATH);
len=strlen(remote.sun_path)+sizeof(remote.sun_family);
if(connect(s1,(struct sockaddr*)&remote,len)==-1)
{
perror("connect");
exit(1);
}
printf("Connectd\n");
while(printf("->"),fgets(str,100,stdin),!feof(stdin))
{
if(send(s1,str,strlen(str),0)==-1)
{
perror("send");
exit(1);
}
19
if((t=recv(s1,str,100,0))>0)
{
str[t]='\0';
printf(" echo->%s",str);
}
else
{
if(t<0)
perror("recv");
else
printf("server closed connection\n");
exit(1);
}
}
close(s1);
return 0;
}
OUTPUT :-
20
XIV.
AIM :- Write a C program to simulate producer and consumer problem using
muexes, shared memory, and threads.
PROGRAM :#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include "buffer.h"
#define RAND_DIVISOR 100000000
#define TRUE 1
pthread_mutex_t mutex;
sem_t full, empty;
buffer_item buffer[BUFFER_SIZE];
int counter;
pthread_t tid;
//Thread ID
pthread_attr_t attr; //Set of thread attributes
void *producer(void *param); /* the producer thread */
void *consumer(void *param); /* the consumer thread */
void initializeData()
{
pthread_mutex_init(&mutex, NULL);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);
pthread_attr_init(&attr);
counter = 0;
}
void *producer(void *param)
{
buffer_item item;
while(TRUE)
{
int rNum = rand() / RAND_DIVISOR;
sleep(rNum);
item = rand();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(insert_item(item))
{
fprintf(stderr, " Producer report error condition\n");
21
}
else {
printf("producer produced %d\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *param)
{
buffer_item item;
while(TRUE)
{
int rNum = rand() / RAND_DIVISOR;
sleep(rNum);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(&item)) {
fprintf(stderr, "Consumer report error condition\n");
}
else {
printf("consumer consumed %d\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int insert_item(buffer_item item) {
if(counter < BUFFER_SIZE)
{
buffer[counter] = item;
counter++;
return 0;
}
else
{ /* Error the buffer is full */
return -1;
}
}
int remove_item(buffer_item *item)
22
{
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else
{ /* Error buffer empty */
return -1;
}
}
int main(int argc, char *argv[])
{
int i;
if(argc != 4)
{
fprintf(stderr, "USAGE:./main.out <INT> <INT> <INT>\n");
}
int mainSleepTime = atoi(argv[1]); /* Time in seconds for main to sleep */
int numProd = atoi(argv[2]); /* Number of producer threads */
int numCons = atoi(argv[3]); /* Number of consumer threads */
initializeData();
for(i = 0; i < numProd; i++)
{
pthread_create(&tid,&attr,producer,NULL);
}
for(i = 0; i < numCons; i++)
{
pthread_create(&tid,&attr,consumer,NULL);
}
sleep(mainSleepTime);
printf("Exit the program\n");
exit(0);
}
OUTPUT :-
23
XV.
AIM :- Write a C program to simulate producer and consumer problem using
semaphores, shared memory, and pthread_create.
PROGRAM :#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include "buffer.h"
#define SUMSIZE 5
#define BUFSIZE 8
int *buffer[BUFSIZE];
int bufin = 0;
int bufout = 0;
pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER;
void get_item(int *item)
{
pthread_mutex_lock(&buffer_lock);
*item = *buffer[bufout];
bufout = (bufout + 1)%BUFSIZE;
pthread_mutex_unlock(&buffer_lock);
}
void put_item(int *item)
{
pthread_mutex_lock(&buffer_lock);
buffer[bufin]= item;
printf("put_item: %dn",item[0]);
bufin = (bufin + 1)%BUFSIZE;
pthread_mutex_unlock(&buffer_lock);
}
int sum = 0;
pthread_cond_t slots = PTHREAD_COND_INITIALIZER;
pthread_cond_t items = PTHREAD_COND_INITIALIZER;
pthread_mutex_t slot_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t item_lock = PTHREAD_MUTEX_INITIALIZER;
int nslots = BUFSIZE;
int producer_done = 0;
int nitems = 0;
void *producer(void *arg)
{
24
int b[1];
int i;
for (i=1;i<=SUMSIZE;i++) {
pthread_mutex_lock(&slot_lock);
while (nslots <= 0)
pthread_cond_wait(&slots, &slot_lock);
nslots--;
pthread_mutex_unlock(&slot_lock);
b[0]=i;
put_item(b);
pthread_mutex_lock(&item_lock);
nitems++;
pthread_cond_signal(&items);
pthread_mutex_unlock(&item_lock);
}
pthread_mutex_lock(&item_lock);
producer_done = 1;
pthread_cond_broadcast(&items);
pthread_mutex_unlock(&item_lock);
return NULL;
}
void *consumer(void *arg2)
{
int *myitem[1];
while (1) {
pthread_mutex_lock(&item_lock);
while ((nitems <= 0) &&!producer_done)
pthread_cond_wait(&items, &item_lock);
if ((nitems <= 0) && producer_done) {
pthread_mutex_unlock(&item_lock);
break;
}
nitems--;
pthread_mutex_unlock(&item_lock);
get_item(myitem);
printf("consumed: %dn",myitem[0]);
pthread_mutex_lock(&slot_lock);
nslots++;
pthread_cond_signal(&slots);
pthread_mutex_unlock(&slot_lock);
25
}
return NULL;
}
int main()
{
pthread_t prodtid;
pthread_t constid;
int i, total;
pthread_create(&prodtid, NULL, producer, NULL);
pthread_create(&constid, NULL, consumer, NULL);
pthread_join(prodtid,NULL);
pthread_join(constid,NULL);
return 0;
}
OUTPUT :-
26
XVI.
AIM :- Write a code simulating ARP/RARP.
PROGRAM :#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<string.h>
main()
{
int shmid,a,i;
char *ptr,*shmptr;
shmid=shmget(3000,10,IPC_CREAT|0666);
shmptr=shmat(shmid,NULL,0);
ptr=shmptr;
for(i=0;i<3;i++)
{
puts("Enter the name:");
scanf("%s",ptr);
a=strlen(ptr);
printf("String length:%d",a);
ptr[a]=' ';
puts("Enter ip:");
ptr=ptr+a+1;
scanf("%s",ptr);
ptr[a]='\n';
ptr=ptr+a+1;
}
ptr[strlen(ptr)]='\0';
printf("\nARP table at serverside is=\n%s",shmptr);
shmdt(shmptr);
}
OUTPUT :-
27
XVII.
AIM :- Write a C program which emulates simple shell.
PROGRAM :#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 :-
28
XVIII.
AIM :- Write C program to create a thread using pthreads library and let it run its
function.
PROGRAM :#include <pthread.h>
#include <stdio.h>
/* this function is run by the second thread */
void *inc_x(void *x_void_ptr)
{
/* increment x to 100 */
int *x_ptr = (int *)x_void_ptr;
while(++(*x_ptr) < 100);
printf("x increment finished\n");
/* the function must return something - NULL will do */
return NULL;
}
int main()
{
int x = 0, y = 0;
/* show the initial values of x and y */
printf("x: %d, y: %d\n", x, y);
/* this variable is our reference to the second thread */
pthread_t inc_x_thread;
/* create a second thread which executes inc_x(&x) */
if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
/* increment y to 100 in the first thread */
while(++y < 100);
printf("y increment finished\n");
/* wait for the second thread to finish */
if(pthread_join(inc_x_thread, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
/* show the results - x is now 100 thanks to the second thread */
printf("x: %d, y: %d\n", x, y);
return 0;
}
29
OUTPUT :-
30
XIX.
AIM :- 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 <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++;
31
if((n= = -1)&(count= =0))
printf(“\n No Message Queue on Queue:%d”,mid);
}
OUTPUT :-
32
XX.
AIM :PROGRAM :OUTPUT :-
Download