[go: up one dir, main page]

0% found this document useful (0 votes)
16 views17 pages

3 Weeks Programs

The document contains several C programs demonstrating the use of UNIX/Linux system calls such as open, read, write, close, fcntl, seek, stat, opendir, and readdir. It also includes examples of implementing the Banker's algorithm for deadlock avoidance and prevention in a simulated environment. Each program is accompanied by explanations and expected outputs.

Uploaded by

gundasreeja6
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)
16 views17 pages

3 Weeks Programs

The document contains several C programs demonstrating the use of UNIX/Linux system calls such as open, read, write, close, fcntl, seek, stat, opendir, and readdir. It also includes examples of implementing the Banker's algorithm for deadlock avoidance and prevention in a simulated environment. Each program is accompanied by explanations and expected outputs.

Uploaded by

gundasreeja6
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/ 17

2.

Write programs using the I/O system calls of UNIX/LINUX operating system(open, read,
write, close, fcntl, seek, stat, opendir, readdir)
open()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
// Open a source file for reading
int source_fd = open("source.txt", O_RDONLY);
if (source_fd == -1)
{
perror("Failed to open source.txt");
exit(1);
}
// Create or open a destination file for writing
int dest_fd = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1)
{
perror("Failed to open destination.txt");
close(source_fd); // Close the source file
exit(1);
}
// Read from the source file and write to the destination file
char buffer[4096]; // A buffer to hold data
ssize_t nread;
while ((nread = read(source_fd, buffer, sizeof(buffer))) > 0)
{
if (write(dest_fd, buffer, nread) != nread)
{
perror("Write error");
break;
}
}
// Check if there was an error during reading
if (nread < 0)
{
perror("Read error");
}
// Close both files
close(source_fd);
close(dest_fd);
return 0;
}

Description:

Standard File Descriptors: When a process starts, it automatically has three standard file descriptors
open: 0, 1, and 2. These are often referred to as stdin (0), stdout (1), and stderr (2). By default, each of
these descriptors points to a file table entry for a file named /dev/tty.

/dev/tty: This is an in-memory surrogate for the terminal. In other words, it’s a representation in the
computer’s memory that stands for the terminal device. The terminal, in this context, is a combination
of a keyboard and a video screen where the user interacts with the system.

1. Read from stdin (fd 0):


When you type on the keyboard, the program reads from standard input (stdin), linked to file
descriptor 0, and saves it from the file named /dev/tty.
2. Write to stdout (fd 1):
Output you see on the screen is written to standard output (stdout), associated with file
descriptor 1, and comes from the file named /dev/tty.
3. Write to stderr (fd 2):
Error messages you see on the screen are written to standard error (stderr), linked to file
descriptor 2, and also come from the file named /dev/tty.

/ C program to illustrate
// open system call
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

extern int errno;

int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);

printf("fd = %d\n", fd);

if (fd == -1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);

// print program detail "Success or failure"


perror("Program");
}
return 0;
}

OUTPUT
// C program to illustrate close system Call
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
int fd1 = open("foo.txt", O_RDONLY);
if (fd1 < 0)
{
perror("c1");
exit(1);
}
printf("opened the fd = % d\n", fd1);

// Using close system Call


if (close(fd1) < 0)
{
perror("c1");
exit(1);
}
printf("closed the fd.\n");
}

OUTPUT
Read() system call:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define BUFFER_SIZE 1024

int main() {
int fd;
char buffer[BUFFER_SIZE];
ssize_t bytes_read;

// Open the file for reading


fd = open("myfile.txt", O_RDONLY); // Replace "myfile.txt" with the actual filename

if (fd == -1)
{

perror("open"); // Print error message using perror


exit(1);
}

// Read from the file


bytes_read = read(fd, buffer, BUFFER_SIZE);

if (bytes_read == -1)
{
perror("read");
close(fd); // Important: Close the file descriptor on error
exit(1);
}

if (bytes_read == 0)
{
printf("End of file reached.\n");
}
else
{
printf("Bytes read: %zd\n", bytes_read);
printf("Content read:\n");

// Important: Null-terminate the buffer if it contains text


// and you intend to print it as a string. read() doesn't
// guarantee null termination.
if (bytes_read < BUFFER_SIZE)
{
buffer[bytes_read] = '\0'; // Add null terminator if it fits
}
else
{
buffer[BUFFER_SIZE -1] = '\0'; // Null terminate the buffer if it is full. You
may not get the complete string if the file is larger than the buffer.
printf("Warning: Buffer full. Content may be truncated\n");
}
printf("%s", buffer); // Print the content
}

// Close the file descriptor


if (close(fd) == -1)
{
perror("close");
exit(1);
}

return 0;
}

Output
Write() system call

// C program to illustrate
// write system Call
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int main()
{
const char *filename = "my_file.txt";
const char *message = "Hello, world! This is a test.\n";
int fd;
ssize_t bytes_written;

// Open the file for writing. O_WRONLY means write-only.


// O_CREAT will create the file if it doesn't exist.
// O_TRUNC will truncate the file to zero length if it exists.
// 0644 are the file permissions (read/write for owner, read for group/others).
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (fd == -1)
{
perror("open"); // Print an error message using perror
fprintf(stderr, "Error opening file: %s\n", strerror(errno)); // More detailed error info
exit(EXIT_FAILURE);
}

// Write the message to the file.


bytes_written = write(fd, message, strlen(message));

if (bytes_written == -1)
{
perror("write");
fprintf(stderr, "Error writing to file: %s\n", strerror(errno));
close(fd); // Important: Close the file descriptor on error
exit(EXIT_FAILURE);
}

if (bytes_written != strlen(message))
{
fprintf(stderr, "Error: Wrote %zd bytes, expected %zu\n", bytes_written,
strlen(message));
close(fd);
exit(EXIT_FAILURE);
}

printf("Successfully wrote %zd bytes to %s\n", bytes_written, filename);

// Close the file. Always close files when you're done with them.
if (close(fd) == -1)
{
perror("close");
fprintf(stderr, "Error closing file: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
return 0;
}

OUTPUT
Example programs demonstrating the use of fcntl, seek, stat, opendir, and readdir in C.

Fcntl()
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
int fd, flags;

fd = open("example.txt", O_RDWR | O_CREAT, 0666);


if (fd == -1)
{
perror("open");
return 1;
}

flags = fcntl(fd, F_GETFL, 0);


if (flags == -1)
{
perror("fcntl");
close(fd);
return 1;
}

flags |= O_APPEND;
if (fcntl(fd, F_SETFL, flags) == -1)
{
perror("fcntl");
close(fd);
return 1;
}

write(fd, "This will be appended\n", 21);

close(fd);
return 0;
}
seek()

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
int fd;
off_t offset;
char buffer[20];
ssize_t bytes_read;

fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}

offset = lseek(fd, 5, SEEK_SET);


if (offset == -1)
{
perror("lseek");
close(fd);
return 1;
}

bytes_read = read(fd, buffer, 10);


if (bytes_read == -1)
{
perror("read");
close(fd);
return 1;
}
buffer[bytes_read] = '\0';
printf("Read from offset 5: %s\n", buffer);

close(fd);
return 0;
}

OUTPUT
stat()

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

int main()
{
struct stat file_info;

if (stat("example.txt", &file_info) == -1)


{
perror("stat");
return 1;
}

printf("File size: %ld bytes\n", file_info.st_size);


printf("Last modified: %s", ctime(&file_info.st_mtime));

return 0;
}

OUTPUT
opendir() and readdir()

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

int main()
{
DIR *dir;
struct dirent *entry;

dir = opendir(".");
if (dir == NULL)
{
perror("opendir");
return 1;
}
errno = 0;
while ((entry = readdir(dir)) != NULL)
{
printf("%s\n", entry->d_name);
}
if (errno != 0)
{
perror("readdir");
closedir(dir);
return 1;
}

closedir(dir);
return 0;
}

OPUTPUT
3. Write a C Program to simulate Bankers algorithm for Deadlock Avoidance and Prevention.

Deadlock Prevention

#include<stdio.h>
#include<conio.h>
#define s 15
void main()
{
int n,m,a[5],e[5],c[5][5],r[5][5];
int i,j,k,cou,l,flag,count;
cou=flag=count=0;
printf("enter no of processes: ");
scanf("%d",&n);
printf("enter no of resource classes: ");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("\n enter instances of resources class %d ",i+1);
scanf("%d",&e[i]);
printf("\n enter free vectors of resources class %d (resources available):",i+1);
scanf("%d",&a[i]);
}
printf("\n enter the current allocation matrix \n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&c[i][j]);
printf("\n enter the request matrix \n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&r[i][j]);
for(l=0;l<n;l++)
{
cou=0;flag=0;
for(i=0;i<n;i++)
{
cou=0;flag=0;
for(j=0;j<m;j++)
if(a[j]>=r[i][j])
{
cou++;
if(c[i][j]==-1)
flag++;
}
if(cou==m)
{
if(flag!=m)
{
printf("\n process %d is satisfied",i+1);
count++;
for(k=0;k<m;k++)
{
a[k]+=c[i][k];
printf("\n a[%d]=%d \t",k,a[k]);
getch();
c[i][k]=-1;
}
}
}
}
}
if(count==n)
printf("\n process sre completed \n");
else
printf("\n unsafe state occurs \n");
getch();
}
INPUT AND OUTPUT
Deadlock Avoidance
#include<stdio.h>
int main()
{
int n,r,i,j,k,p,u=0,s=0,m;
int block[10],run[10],active[10],newreq[10];
int max[10][10],resalloc[10][10],resreq[10][10];
int totalloc[10],totext[10],simalloc[10];
printf("Enter the no of processes:");
scanf("%d",&n);
printf("Enter the no ofresource classes:");
scanf("%d",&r);
printf("Enter the total existed resource in each class:");
for(k=1; k<=r; k++)
scanf("%d",&totext[k]);
printf("Enter the allocated resources:");
for(i=1; i<=n; i++)
for(k=1; k<=r; k++)
scanf("%d",&resalloc[i][k]);
printf("Enter the process making the new request:");
scanf("%d",&p);
printf("Enter the requested resource:");
for(k=1; k<=r; k++)
scanf("%d",&newreq[k]);
printf("Enter the process which are n blocked or running:");
for(i=1; i<=n; i++)
{
if(i!=p)
{
printf("process %d:\n",i+1);
scanf("%d%d",&block[i],&run[i]);
}
}
block[p]=0;
run[p]=0;
for(k=1; k<=r; k++)
{
j=0;
for(i=1; i<=n; i++)
{
totalloc[k]=j+resalloc[i][k];
j=totalloc[k];
}
}
for(i=1; i<=n; i++)
{
if(block[i]==1||run[i]==1)
active[i]=1;
else
active[i]=0;
}
for(k=1; k<=r; k++)
{
resalloc[p][k]+=newreq[k];
totalloc[k]+=newreq[k];
}
for(k=1; k<=r; k++)
{
if(totext[k]-totalloc[k]<0)
{
u=1;
break;
}
}
if(u==0)
{
for(k=1; k<=r; k++)
simalloc[k]=totalloc[k];
for(s=1; s<=n; s++)
for(i=1; i<=n; i++)
{
if(active[i]==1)
{
j=0;
for(k=1; k<=r; k++)
{
if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k]))
{
j=1;
break;
}
}
}
if(j==0)
{
active[i]=0;
for(k=1; k<=r; k++)
simalloc[k]=resalloc[i][k];
}
}
m=0;
for(k=1; k<=r; k++)
resreq[p][k]=newreq[k];
printf("Deadlock willn't occur");
}
else
{
for(k=1; k<=r; k++)
{
resalloc[p][k]=newreq[k];
totalloc[k]=newreq[k];
}
printf("Deadlock will occur");
}
return 0;
}

INPUT / OUTPUT

You might also like