-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfg_bg.c
73 lines (68 loc) · 1.71 KB
/
fg_bg.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
#include "headers.h"
extern struct BackgroundProcess bgProcesses[MAX_COMMANDS];
extern int numBgProcesses;
void handle_fg(char *command)
{
int pid;
if (sscanf(command, "fg %d", &pid) == 1)
{
// Find the process with the given PID
bool found = false;
for (int i = 0; i < numBgProcesses; i++)
{
if (bgProcesses[i].pid == pid)
{
found = true;
bringToForeground(pid);
printf("[%d] : %s - Running\n", bgProcesses[i].pid, bgProcesses[i].name);
break;
}
}
if (!found)
{
printf("No such process found\n");
}
}
}
void handle_bg(char *command)
{
int pid;
if (sscanf(command, "bg %d", &pid) == 1)
{
// Find the process with the given PID
bool found = false;
for (int i = 0; i < numBgProcesses; i++)
{
if (bgProcesses[i].pid == pid)
{
found = true;
resumeBackgroundProcess(pid);
printf("[%d] : %s - Running (in the background)\n", bgProcesses[i].pid, bgProcesses[i].name);
break;
}
}
if (!found)
{
printf("No such process found\n");
}
}
}
int bringToForeground(pid_t pid)
{
if (pid > 0)
{
// Send a SIGCONT signal to the process to resume it if stopped
kill(pid, SIGCONT);
// Wait for the process to complete
int status;
waitpid(pid, &status, WUNTRACED);
}
}
int resumeBackgroundProcess(pid_t pid)
{
if (pid > 0)
{
// Send a SIGCONT signal to the process to resume it
kill(pid, SIGCONT);
}
}