Banker's Algorithmsssss
1#include <stdio.h>
2
3int main() {
4 int n = 5; // Number of processes
5 int m = 3; // Number of resource types
6 int i, j, k;
7
8 int alloc[5][3] = {
9 { 0, 1, 0 }, // P0
10 { 2, 0, 0 }, // P1
11 { 3, 0, 2 }, // P2
12 { 2, 1, 1 }, // P3
13 { 0, 0, 2 } // P4
14 };
15
16 int max[5][3] = {
17 { 7, 5, 3 }, // P0
18 { 3, 2, 2 }, // P1
19 { 9, 0, 2 }, // P2
20 { 2, 2, 2 }, // P3
21 { 4, 3, 3 } // P4
22 };
23
24 int avail[3] = { 3, 3, 2 }; // Available Resources
25
26 int newRequest[5][3] = {0}, ProNo;
27
28 printf("Banker's Algorithm\n");
29
30 printf("For the new request: enter process number (0 to 4)\n");
31 scanf("%d", &ProNo);
32
33 printf("Enter the new request of process P%d in the order resources [A B C]\n", ProNo);
34 scanf("%d", &newRequest[ProNo][0]);
35 scanf("%d", &newRequest[ProNo][1]);
36 scanf("%d", &newRequest[ProNo][2]);
37
38 // Check if request is less than or equal to available
39 if (newRequest[ProNo][0] > avail[0] ||
40 newRequest[ProNo][1] > avail[1] ||
41 newRequest[ProNo][2] > avail[2]) {
42 printf("Request cannot be granted now as it exceeds available resources.\n");
43 printf("Process must wait.\n");
44 return 0;
45 }
46
47 // Pretend allocation
48 avail[0] -= newRequest[ProNo][0];
49 avail[1] -= newRequest[ProNo][1];
50 avail[2] -= newRequest[ProNo][2];
51
52 alloc[ProNo][0] += newRequest[ProNo][0];
53 alloc[ProNo][1] += newRequest[ProNo][1];
54 alloc[ProNo][2] += newRequest[ProNo][2];
55
56 // Calculate need matrix
57 int need[n][m];
58 for (i = 0; i < n; i++) {
59 for (j = 0; j < m; j++) {
60 need[i][j] = max[i][j] - alloc[i][j];
61 }
62 }
63
64 int f[n], ans[n], ind = 0;
65 for (k = 0; k < n; k++) {
66 f[k] = 0;
67 }
68
69 int flag;
70 int y = 0;
71
72 for (k = 0; k < 5; k++) {
73 for (i = 0; i < n; i++) {
74 if (f[i] == 0) {
75 flag = 0;
76 for (j = 0; j < m; j++) {
77 if (need[i][j] > avail[j]) {
78 flag = 1;
79 break;
80 }
81 }
82 if (flag == 0) {
83 ans[ind++] = i; // Safe sequence
84 for (y = 0; y < m; y++) {
85 avail[y] += alloc[i][y];
86 }
87 f[i] = 1;
88 }
89 }
90 }
91 }
92
93 int safe = 1;
94 for (i = 0; i < n; i++) {
95 if (f[i] == 0) {
96 safe = 0;
97 break;
98 }
99 }
100
101 if (safe == 0) {
102 printf("Request cannot be granted now, as it may lead to Deadlock.\n");
103 printf("There is no safe sequence.\n");
104 printf("Your request is not granted to avoid Deadlock.\n");
105 printf("Process has to wait.\n");
106 } else {
107 printf("Request can be granted, as a safe sequence is present.\n");
108 printf("There will be no deadlock.\n");
109 printf("Following is the SAFE Sequence:\n");
110 for (i = 0; i < n - 1; i++)
111 printf("P%d -> ", ans[i]);
112 printf("P%d\n", ans[n - 1]);
113 }
114
115 return 0;
116}
OUTPUTBanker's AlgorithmFor the new request: enter process number (0 to 4)1Enter the new request of process P1 in the order resources [A B C]102Request can be granted, as a safe sequence is present.There will be no deadlock.Following is the SAFE Sequence:P1 -> P3 -> P4 -> P0 -> P2
Producer Consumer Problem
1#include<unistd.h>
2#include<stdio.h>
3#include<pthread.h>
4#include<semaphore.h>
5int buf[5], f, r; //Circular queue
6sem_t mutex, full, empty;
7void *produce(void *arg)
8{
9 int i;
10 for(i=0;i<10;i++)
11 {
12 sem_wait(&empty);//Wait of empty slot and decrement the empty
13 sem_wait(&mutex); //Wait if consumer is comsuming a item
14
15 printf("produced item is %d\n",i);
16 buf[(++r)%5]=i;
17 sleep(1);
18
19 sem_post(&mutex); // signal the consumer to consume the item mutex=0
20 sem_post(&full); // full will be increamented
21
22 }
23}
24void *consume(void *arg)
25{
26 int item,i;
27 for(i=0;i<10;i++)
28 {
29 sem_wait(&full); //Wait for item and decrement the full
30 sem_wait(&mutex); // Wait if producer s producing a item
31
32 item=buf[(++f)%5];
33 printf("consumed item is %d\n",item);
34 sleep(1);
35
36 sem_post(&mutex); // signal the producer to produce the item mutex=0
37 sem_post(&empty); // incrementing the empty variable
38 }
39}
40int main()
41{
42 pthread_t tid1,tid2;
43 sem_init(&mutex, 0, 1);
44 sem_init(&full, 0, 0);
45 sem_init(&empty, 0, 5);
46 pthread_create(&tid1, NULL, produce, NULL);
47 pthread_create(&tid2,NULL, consume, NULL);
48 pthread_join(tid1,NULL);
49 pthread_join(tid2,NULL);
50
51 return 0;
52}
OUTPUTproduced item is 0produced item is 1produced item is 2produced item is 3produced item is 4consumed item is 0consumed item is 1consumed item is 2^C
Paging technique of memory management
1#include<stdio.h>
2int main()
3{
4int ms, Fsize, NoFrames, NoProcess, RemFrames, i, j, x, y, pa, offset;
5int NoPages, PageTable[10];
6printf("\nEnter the memory size -- ");
7scanf("%d", &ms);
8printf("\nEnter the Frame size -- ");
9scanf("%d", &Fsize);
10NoFrames = ms/Fsize;
11printf("\n The no. of Frames available in memory are -- %d ", NoFrames);
12 RemFrames = NoFrames;
13
14 printf("\n Enter no. of pages required : ");
15 scanf("%d", &NoPages);
16
17 if(NoPages >RemFrames)
18 {
19 printf("\n Memory is Full");
20 return (0);
21 }
22 RemFrames = RemFrames - NoPages;
23 printf("\n ---Enter page table --- ");
24 for(j=0;j<NoPages;j++)
25 scanf("%d", &PageTable[j]);
26
27 printf("\n ---page table --- ");
28 printf(" \n| PNo || FNo |");
29 for(j=0;j<NoPages;j++)
30 printf(" \n| %d || %d |",j,PageTable[j]);
31
32 int yes=1;
33 do
34 {
35 printf("\nEnter Logical Address to find Physical Address ");
36 printf("\nEnter page number and offset -- ");
37 scanf(" %d %d",&y, &offset);
38 if( y>=NoPages || offset>=Fsize)
39 {
40 printf("\n trap: Page Number or offset illegal");
41 return(0);
42 }
43 else
44 {
45 pa = (PageTable[y]*Fsize) + offset;
46
47 printf("Fsize=%d,offset=%d\n,frame no=%d",Fsize,offset,PageTable[y]);
48 printf("\n The Physical Address is -- %d", pa);
49 }
50 printf("\nContinue : yes=1,no=0\n");
51 scanf("%d",&yes);
52
53 }while(yes==1);
54
55 return 0;
56}
OUTPUTEnter the memory size -- 32Enter the Frame size -- 4The no. of Frames available in memory are -- 8Enter no. of pages required : 4---Enter page table --- 5612---page table ---| PNo || FNo || 0 || 5 || 1 || 6 || 2 || 1 || 3 || 2 |Enter Logical Address to find Physical AddressEnter page number and offset -- 0 0Fsize=4,offset=0,frame no=5The Physical Address is -- 20Continue : yes=1,no=01Enter Logical Address to find Physical AddressEnter page number and offset -- 1 3Fsize=4,offset=3,frame no=6The Physical Address is -- 27Continue : yes=1,no=0^C
Segmentation technique of Memory Management
1#include<stdio.h>
2int main()
3{
4 int i, y, PhyAddre, offset;
5 int NoSeg, SegmentTable[10][10];
6
7 printf("\nEnter number segments -- ");
8 scanf("%d", &NoSeg);
9 printf("\nEnter the Segmentation Table data: Base value & Limit Value\n -- ");
10 for(i=0;i<NoSeg;i++)
11 scanf("%d%d", &SegmentTable[i][0],&SegmentTable[i][1]);
12
13 printf("\n----Enter the Segmentation Table data---\n");
14 printf("Segment NO || Base || Limit || \n");
15 for(i=0;i<NoSeg;i++)
16 printf("|| %d || %d || %d || \n",i,SegmentTable[i][0],SegmentTable[i][1]);
17
18 int yes=1;
19
20do
21 {
22 printf("\nEnter Logical Address to find Physical Address ");
23 printf("\nEnter segment number and offset\n ");
24 scanf(" %d %d",&y, &offset);
25
26 if(offset>SegmentTable[y][1])
27 {
28 printf("Trap : Addressing Error\n");
29 }
30 else
31 {
32 PhyAddre=SegmentTable[y][0]+offset;
33 printf("\n The Physical Address is -- %d", PhyAddre);
34 printf("\nContinue : yes=1,no=0\n");
35 scanf("%d",&yes);
36 }
37 }while(yes==1);
38
39 return 0;
40}
OUTPUTEnter number of segments -- 5Enter the Segmentation Table data: Base value & Limit Value--219 6002300 1490 1001327 5801952 96----Enter the Segmentation Table data---Segment NO || Base || Limit |||| 0 || 219 || 600 |||| 1 || 2300 || 14 |||| 2 || 90 || 100 |||| 3 || 1327 || 580 |||| 4 || 1952 || 96 ||Enter Logical Address to find Physical AddressEnter segment number and offset0 430The Physical Address is -- 649Continue : yes=1,no=01Enter Logical Address to find Physical AddressEnter segment number and offset1 10The Physical Address is -- 2310Continue : yes=1,no=01Enter Logical Address to find Physical Address
Enter segment number and offset2 500Trap : Addressing ErrorContinue : yes=1,no=0^C
Page Replacement Policies (FCFS)
1#include<stdio.h>
2int main()
3{
4 int i,j,n,a[50],frame[10],no,k,avail,count=0;
5 printf("\n ENTER THE NUMBER OF PAGES:\n");
6 scanf("%d",&n);
7 printf("\n ENTER THE PAGE NUMBER :\n");
8 for(i=1;i<=n;i++)
9 scanf("%d",&a[i]);
10
11 printf("\n ENTER THE NUMBER OF FRAMES :");
12 scanf("%d",&no);
13
14 for(i=0;i<no;i++)
15 frame[i]= -1;
16 j=0;
17 printf("\tref string\t page frames\n");
18
19 for(i=1;i<=n;i++)
20 {
21 printf("%d\t\t",a[i]);
22 avail=0;
23 for(k=0;k<no;k++)
24 if(frame[k]==a[i])
25 avail=1;
26 if (avail==0)
27 {
28 frame[j]=a[i];
29 j=(j+1)%no;
30 count++;
31 for(k=0;k<no;k++)
32 printf("%d\t",frame[k]);
33 }
34 printf("\n");
35 }
36 printf("Page Fault Is %d",count);
37 return 0;
38}
OUTPUTENTER THE NUMBER OF PAGES: 20ENTER THE PAGE NUMBER : 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1ENTER THE NUMBER OF FRAMES :3ref string page frames7 7 -1 -10 7 0 -11 7 0 12 2 0 103 2 3 10 2 3 04 4 3 02 4 2 03 4 2 30 0 2 332 1 0 1 32 0 1 2017 7 1 20 7 0 21 7 0 1Page Fault Is 15
FCFS Scheduling Algorithm
1#include<stdio.h>
2int main()
3{
4int processes[] = { 1, 2, 3};
5int n =3;
6 int bt[] = {10, 5, 8};
7
8 int wt[n], tat[n], total_wt = 0, total_tat = 0;
9
10 wt[0] = 0;
11
12 // calculating waiting time
13 for (int i = 1; i < n ; i++ )
14 wt[i] = bt[i-1] + wt[i-1] ;
15
16 // calculating turnaround time
17 for (int i = 0; i < n ; i++)
18 tat[i] = bt[i] + wt[i];
19
20 //Display processes along with all details
21 printf("Processes Burst time Waiting time Turn around time\n");
22
23 // Calculate total waiting time and total turn
24 // around time
25 for (int i=0; i<n; i++)
26 {
27 total_wt = total_wt + wt[i];
28 total_tat = total_tat + tat[i];
29 printf(" %d ",(i+1));
30 printf(" %d ", bt[i] );
31 printf(" %d",wt[i] );
32 printf(" %d\n",tat[i] );
33 }
34 int s=(float)total_wt / (float)n;
35 int t=(float)total_tat / (float)n;
36 printf("Average waiting time = %d",s);
37 printf("\n");
38 printf("Average turn around time = %d ",t);
39
40 return 0;
41}
OUTPUTRUN 1:Processes Burst time Waiting time Turn around time1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8
Average turn around time = 16
SJF Scheduling Algorithm
1#include <stdio.h>
2#define MAX 15
3
4struct process {
5 int pid;
6 int bt;
7 int wt;
8 int tt;
9};
10
11int main() {
12 struct process proc[MAX], temp;
13 int n, i, j;
14 int total_wt = 0, total_tt = 0;
15 float avg_wt, avg_tt;
16
17 printf("Enter number of processes (max 15): ");
18 scanf("%d", &n);
19
20 printf("Enter Process ID and Burst Time:\n");
21 for (i = 0; i < n; i++) {
22 scanf("%d %d", &proc[i].pid, &proc[i].bt);
23 }
24
25 // Sort processes by burst time using bubble sort
26 for (i = 0; i < n - 1; i++) {
27 for (j = 0; j < n - i - 1; j++) {
28 if (proc[j].bt > proc[j + 1].bt) {
29 temp = proc[j];
30 proc[j] = proc[j + 1];
31 proc[j + 1] = temp;
32 }
33 }
34 }
35
36 // Calculate waiting time and turnaround time
37 for (i = 0; i < n; i++) {
38 if (i == 0) {
39 proc[i].wt = 0;
40 } else {
41 proc[i].wt = proc[i - 1].wt + proc[i - 1].bt;
42 }
43
44 proc[i].tt = proc[i].wt + proc[i].bt;
45 total_wt += proc[i].wt;
46 total_tt += proc[i].tt;
47 }
48
49 avg_wt = (float)total_wt / n;
50 avg_tt = (float)total_tt / n;
51
52 printf("\nProcess ID Burst Time Waiting Time Turnaround Time\n");
53 for (i = 0; i < n; i++) {
54 printf("%9d %10d %13d %16d\n", proc[i].pid, proc[i].bt, proc[i].wt, proc[i].tt);
55 }
56
57 printf("\nAverage Waiting Time = %.2f\n", avg_wt);
58 printf("Average Turnaround Time = %.2f\n", avg_tt);
59
60 return 0;
61}
OUTPUTEnter number of processes (max 15): 4Enter Process ID and Burst Time:2 4 53 5 61 7 8Process ID Burst Time Waiting Time Turnaround Time5 3 0 32 4 3 75 6 7 131 7 13 20
Average Waiting Time = 5.75Average Turnaround Time = 10.75
RR (Round Robin) Scheduling Algorithm
1#include <stdio.h>
2#define MAX 15
3
4struct process {
5 int pid;
6 int bt;
7 int wt;
8 int tt;
9 int rem_bt;
10};
11
12int main() {
13 struct process proc[MAX];
14 int n, i, quantum, t = 0;
15 int total_wt = 0, total_tt = 0;
16 float avg_wt, avg_tt;
17 int done;
18
19 printf("Enter number of processes (max 15): ");
20 scanf("%d", &n);
21
22 printf("Enter Process ID and Burst Time:\n");
23 for (i = 0; i < n; i++) {
24 scanf("%d %d", &proc[i].pid, &proc[i].bt);
25 proc[i].rem_bt = proc[i].bt;
26 proc[i].wt = 0; // Initialize waiting time to 0
27 }
28
29 printf("Enter Time Quantum: ");
30 scanf("%d", &quantum);
31
32 printf("\nOrder of Process Execution:\n");
33
34 // Round Robin Scheduling
35 do {
36 done = 1;
37 for (i = 0; i < n; i++) {
38 if (proc[i].rem_bt > 0) {
39 done = 0;
40 printf("P%d ", proc[i].pid);
41
42 if (proc[i].rem_bt > quantum) {
43 t += quantum;
44 proc[i].rem_bt -= quantum;
45 } else {
46 t += proc[i].rem_bt;
47 proc[i].wt = t - proc[i].bt;
48 proc[i].rem_bt = 0;
49 }
50 }
51 }
52 } while (!done);
53
54 // Calculate turnaround time and totals
55 for (i = 0; i < n; i++) {
56 proc[i].tt = proc[i].wt + proc[i].bt;
57 total_wt += proc[i].wt;
58 total_tt += proc[i].tt;
59 }
60
61 avg_wt = (float)total_wt / n;
62 avg_tt = (float)total_tt / n;
63
64 // Print results
65 printf("\n\n| PID | BT | WT | TAT |\n");
66 printf("-------------------------------\n");
67 for (i = 0; i < n; i++) {
68 printf("| %3d | %3d | %3d | %3d |\n", proc[i].pid, proc[i].bt, proc[i].wt, proc[i].tt);
69 }
70
71 printf("\nAverage Waiting Time: %.2f\n", avg_wt);
72 printf("Average Turnaround Time: %.2f\n", avg_tt);
73
74 return 0;
75}
OUTPUTEnter number of processes (max 15): 3Enter Process ID and Burst Time:1 102 53 8Enter Time Quantum: 2Order of Process Execution:P1 P2 P3 P1 P2 P3 P1 P2 P3 P1 P3 P1| PID | BT | WT | TAT |-------------------------------| 1 | 10 | 13 | 23 || 2 | 5 | 10 | 15 || 3 | 8 | 13 | 21 |Average Waiting Time: 12.00Average Turnaround Time: 19.67
Priority Scheduling Algorithm
1#include <stdio.h>
2#define MAX 15
3
4struct process {
5 int pid;
6 int priority;
7 int bt;
8 int wt;
9 int tt;
10};
11
12int main() {
13 struct process proc[MAX], temp;
14 int n, i, j;
15 int total_wt = 0, total_tt = 0;
16 float avg_wt, avg_tt;
17
18 printf("Enter number of processes (max 15): ");
19 scanf("%d", &n);
20
21 printf("Enter Process ID, Burst Time, and Priority for each process:\n");
22 for (i = 0; i < n; i++) {
23 scanf("%d %d %d", &proc[i].pid, &proc[i].bt, &proc[i].priority);
24 }
25
26 // Sort by priority (lower number = higher priority)
27 for (i = 0; i < n - 1; i++) {
28 for (j = 0; j < n - i - 1; j++) {
29 if (proc[j].priority > proc[j + 1].priority) {
30 temp = proc[j];
31 proc[j] = proc[j + 1];
32 proc[j + 1] = temp;
33 }
34 }
35 }
36
37 // Calculate waiting time and turnaround time
38 proc[0].wt = 0;
39 proc[0].tt = proc[0].bt;
40 total_tt = proc[0].tt;
41
42 for (i = 1; i < n; i++) {
43 proc[i].wt = proc[i - 1].wt + proc[i - 1].bt;
44 proc[i].tt = proc[i].wt + proc[i].bt;
45 total_wt += proc[i].wt;
46 total_tt += proc[i].tt;
47 }
48
49 avg_wt = (float)total_wt / n;
50 avg_tt = (float)total_tt / n;
51
52 // Output the table
53 printf("\n| Process ID | Priority | Burst Time | Waiting Time | Turnaround Time |\n");
54 printf("-----------------------------------------------------------------------\n");
55
56 for (i = 0; i < n; i++) {
57 printf("| %3d | %3d | %3d | %3d | %3d |\n",
58 proc[i].pid, proc[i].priority, proc[i].bt, proc[i].wt, proc[i].tt);
59 }
60
61 printf("\nAverage Waiting Time = %.2f\n", avg_wt);
62 printf("Average Turnaround Time = %.2f\n", avg_tt);
63
64 return 0;
65}
OUTPUT
Enter number of processes (max 15): 3Enter Process ID, Burst Time, and Priority for each process:1 10 22 5 13 8 3| Process ID | Priority | Burst Time | Waiting Time | Turnaround Time |-----------------------------------------------------------------------| 2 | 1 | 5 | 0 | 5 || 1 | 2 | 10 | 5 | 15 || 3 | 3 | 8 | 15 | 23 |Average Waiting Time = 6.67Average Turnaround Time = 14.33
Programs to implement following system calls of UNIX operating system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir ,closedir and lseek
Write a C program to read from file and write to another file.
1#include<stdio.h>
2#include<stdlib.h>
3#include<unistd.h>
4#include<fcntl.h>
5#define BUFF_SIZE 1000
6int main(void)
7{
8int n,fd1,fd2;
9char buff[BUFF_SIZE];
10//open the file for reading
11fd1 = open("testfile.txt",O_RDWR,0644);
12//read the data from file
13n=read(fd1,buff,BUFF_SIZE);
14// creating a new file using open.
15fd2=open("fileforcopy.txt", O_CREAT | O_RDWR, 0777);
16//writting data to file (fd)
17if( write(fd2, buff, n) == n)
18printf("file copying is successful. and the data is:\n");
19//Write to display (1 is standard fd for output device)
20write(1, buff, n);
21//closing the files
22int close(int fd1);
23int close(int fd2);
24return 0;
25}
INPUT & OUTPUTtestfile.txt file copied to fileforcopy.txtfile copying is successful. and the data is: hello mgit
Program using lseek() system call that reads 10 characters from file “seeking” and print on screen. Skip next 5 characters and again read 10 characters and write on screen.
1#include <stdio.h> // for perror()
2#include <unistd.h> // for read(), write()
3#include <fcntl.h> // for open()
4#include <sys/types.h> // for types like mode_t
5#include <sys/stat.h> // for file permissions
6
7int main() {
8 int f;
9 char buff[10];
10
11 // Open the file 'seeking' in read-write mode
12 f = open("seeking", O_RDWR);
13 if (f < 0) {
14 perror("Error opening file");
15 return 1;
16 }
17
18 // Read first 10 bytes and write to stdout
19 read(f, buff, 10);
20 write(1, buff, 10);
21
22 // Read next 10 bytes and write to stdout
23 read(f, buff, 10);
24 write(1, buff, 10);
25
26 close(f);
27 return 0;
28}
29
how to execute
echo -n "1234567890abcdefghijxxxxxxxxxx" > seekingnano file_seek.cthen paste code herecompile:gcc file_seek.c -o file_seekrun:./file_seek
OUTPUT1234567890abcdefghij
Write a C program to print file status information using stat function.
1#include<stdio.h>
2#include <sys/types.h>
3#include <sys/stat.h>
4#include <dirent.h>
5#include<unistd.h>
6struct stat statbuf;
7char dirpath[256];
8int main(int argc, char *argv[])
9{
10// getcwd is to get the name of the current working directory if found
11getcwd(dirpath,256);
12DIR *dir = opendir(dirpath);
13struct dirent *dp;
14for (dp=readdir(dir); dp != NULL ; dp=readdir(dir))
15{
16stat(dp->d_name, &statbuf);
17printf("the file name is %s \n", dp->d_name);
18printf("dir = %d\n", S_ISDIR(statbuf.st_mode));
19printf("file size is %ld in bytes \n", statbuf.st_size);
20printf("last modified time is %ld in seconds \n", statbuf.st_mtime);
21printf("last access time is %ld in seconds \n", statbuf.st_atime);
22printf("The device containing the file is %ld\n", statbuf.st_dev);
23printf("File serial number is %ld\n\n", statbuf.st_ino);
24}
25}
OUTPUTthe file name is fileone.txtdir = 0file size is 31 in byteslast modified time is 1581656490 in secondslast access time is 1581656969 in secondsThe device containing the file is 2053File serial number is 2099241the file name is filestatus.cdir = 0file size is 772 in byteslast modified time is 1581146159 in secondslast access time is 1581920990 in secondsThe device containing the file is 2053File serial number is 2099181...(and so on)
how to execute:
nano dirinfo.cthen paste the codecompile: gcc dirinfo.c -o dirinforun: ./dirinfo
Program for opendir(), readdir() and closedir system calls
1#include <stdio.h>
2#include <stdlib.h> // for exit()
3#include <dirent.h> // for DIR, struct dirent
4
5int main(int argc, char *argv[]) {
6 char buff[100];
7 DIR *dirp;
8 struct dirent *dptr;
9
10 printf("\nEnter Directory Name: ");
11 scanf("%s", buff);
12
13 dirp = opendir(buff);
14 if (dirp == NULL) {
15 printf("The given directory does not exist.\n");
16 exit(1);
17 }
18
19 printf("\nFiles in the directory:\n");
20 while ((dptr = readdir(dirp)) != NULL) {
21 printf("%s\n", dptr->d_name);
22 }
23
24 closedir(dirp);
25 return 0;
26}
how to execute:
nano read_dir.cthen paste the codecompile: gcc read_dir.c -o read_dirrun: ./read_dir
OUTPUTEnter Directory Name: .Files in the directory:...read_dirread_dir.csome_other_file.txt
C Program for fork() and getpid() system call
1#include <stdio.h>
2#include <unistd.h>
3#include <stdlib.h> // for exit()
4
5int main() {
6 int pid, pid1, pid2;
7
8 pid = fork(); // create a new process
9
10 if (pid == -1) {
11 printf("ERROR IN PROCESS CREATION\n");
12 exit(1);
13 }
14
15 if (pid != 0) {
16 pid1 = getpid();
17 printf("\nThe parent process ID is %d\n", pid1);
18 } else {
19 pid2 = getpid();
20 printf("\nThe child process ID is %d\n", pid2);
21 }
22
23 return 0;
24}
OUTPUTThe parent process ID is 58936
The child process ID is 58937
how to execute:
save the code: nano fork_demo.ccompile:gcc fork_demo.c -o fork_demorun:./fork_demo
program to execute another C program using exec system call.
first create hello.c
1#include <stdio.h>
2
3int main() {
4 printf("Hello! I am the child program.\n");
5 return 0;
6}
then exec_demo.c
1#include <stdio.h>
2#include <unistd.h>
3#include <stdlib.h>
4#include <sys/wait.h> // Required for wait()
5
6int main() {
7 pid_t pid = fork();
8
9 if (pid < 0) {
10 perror("Fork failed");
11 exit(1);
12 }
13
14 if (pid == 0) {
15 // Child process
16 printf("Child process about to run hello...\n");
17 execl("./hello", "hello", NULL); // Run the other C program
18
19 // If exec fails
20 perror("execl failed");
21 exit(1);
22 } else {
23 // Parent process
24 printf("Parent process waiting for child...\n");
25 wait(NULL);
26 printf("Child process completed.\n");
27 }
28
29 return 0;
30}
how to execute
compile both files: gcc hello.c -o hellogcc exec_demo.c -o exec_demoto run:./exec_demo
OUTPUTParent process waiting for child...Child process about to run hello...Hello! I am the child program.Child process completed.