-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemcall.c
140 lines (129 loc) · 3 KB
/
systemcall.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
PROGRAM:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
int fd;
int forkExecCall()
{
pid_t pid;
int ret = 1;
int status;
pid = fork();
if (pid == -1)
{
printf("can't fork, error occured\n");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
printf("child process, pid = %u\n", getpid());
printf("parent of child process, pid = %u\n", getppid());
char *argv_list[] = {"ls", "-lart", "/home", NULL};
execv("ls", argv_list);
}
else
{
printf("Parent Of parent process, pid = %u\n", getppid());
printf("parent process, pid = %u\n", getpid());
if (waitpid(pid, &status, 0) > 0)
{
if (WIFEXITED(status) && !WEXITSTATUS(status))
printf("---program execution successful---\n");
else if (WIFEXITED(status) && WEXITSTATUS(status))
{
if (WEXITSTATUS(status) == 127)
{
printf("execv failed\n");
}
else
printf("program terminated normally but returned a non-zero status\n");
}
else
printf("program didn't terminate normally\n");
}
else
{
printf("waitpid() failed\n");
}
}
return 0;
}
int forkWaitCall()
{
pid_t cpid;
if (fork() == 0)
exit(0);
else
cpid = wait(NULL);
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);
return 0;
}
int createaFile()
{
fd = open("file1.txt", O_CREAT, 0777);
closeFile();
}
void readFile()
{
char *ch = (char *)calloc(100, sizeof(char));
fd = open("file1.txt", O_RDONLY);
read(fd, ch, 100);
printf("Contents of file1.txt is : \n%s\n\n", ch);
closeFile();
}
void writeFile()
{
char ch[100];
fd = open("file1.txt", O_WRONLY);
printf("Enter text to write in the file file1.txt :\n");
int n = read(0, ch, 100);
write(fd, ch, n);
printf("Written Successfully\n\n");
closeFile();
}
void closeFile()
{
close(fd);
}
int main()
{
int choice;
printf("\nPROGRAM:---SYSTEM CALLS---\n");
while (1)
{
printf("Enter your choice\n1.Fork and Exec\n2.Fork and wait \n3.Create file\n4.Write\n5.Read\n6.Close file\n0.Exit\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
forkExecCall();
break;
case 2:
forkWaitCall();
break;
case 3:
createaFile();
printf("file1.txt created\n\n");
break;
case 4:
writeFile();
break;
case 5:
readFile();
break;
case 6:
closeFile();
printf("closed file1.txt \n\n");
break;
case 0:
exit(0);
}
}
return 0;
}