forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecWithFork.c
50 lines (46 loc) · 952 Bytes
/
execWithFork.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
char userChoice = 'z';
while (userChoice != 'q' && userChoice != 'Q') {
printf("A: ls \n");
printf("B: ps \n");
printf("C: who \n");
printf("Q: quit \n");
printf("Enter a command: ");
scanf(" %c", &userChoice);
pid = fork();
if (pid == 0) {
switch (userChoice) {
case 'a':
case 'A':
execlp("/bin/ls", "ls", NULL);
break;
case 'b':
case 'B':
execlp("/bin/ps", "ps", NULL);
break;
case 'c':
case 'C':
execlp("/usr/bin/whoami", "who", NULL);
break;
case 'q':
case 'Q':
exit(0);
default:
printf("Invalid choice\n");
break;
}
} else if (pid > 0) {
wait(NULL);
} else {
perror("fork");
}
}
printf("Goodbye!\n");
return 0;
}