-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.c
109 lines (97 loc) · 2.65 KB
/
background.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
#include "headers.h"
bgpro backs[N];
int totalpro;
void removepro(int id)
{
for (int i = 0; i < totalpro; ++i)
{
if (backs[i].pid == id)
{
for (int j = i + 1; j < totalpro; ++j)
{
backs[j - 1] = backs[j];
backs[j - 1].proid--;
}
--totalpro;
break;
}
}
}
void checkprocess()
{
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
{
for (int i = 0; i < totalpro; ++i)
{
if (pid == backs[i].pid)
{
if (WIFEXITED(status))
{
char *cmd = backs[i].command;
int exit_code = WEXITSTATUS(status);
if (exit_code == 0)
printf("%s exited normally (%d)\n", cmd, pid);
else
printf("%s exited abnormally (%d)\n", cmd, pid);
removepro(pid); // Remove the process entry once it's done
}
else if (WIFSIGNALED(status))
{
printf("%s terminated by signal (%d)\n", backs[i].command, pid);
removepro(pid);
}
break;
}
}
}
}
void bprocess(char **processes)
{
int start = 0;
while (processes[start] != NULL)
{
char *command = processes[start++];
char *copy = strdup(command); // Tokenization copy
char *ordered[N];
char *dummy[N];
char delimiters[N];
// Tokenize the command
int check = tokenise_for_piping(copy, ordered);
int check2 = tokenise_for_redirection(copy, dummy, delimiters);
if (check == 1)
{
pipehandler(ordered, NULL, 2);
free(copy);
continue;
}
else if (check2 == 1)
{
iohandler(command, NULL, NULL, 2);
free(copy);
continue;
}
pid_t pid = fork();
if (pid < 0)
{
perror("Fork unsuccessful");
}
else if (pid == 0)
{
setsid(); // Create a new session so it runs independently in background
run_command(command);
exit(0);
}
else
{
backs[totalpro].pid = pid;
backs[totalpro].command = strdup(strtok(command, " \t\n"));
backs[totalpro].proid = totalpro++;
printf("Started background process: %s (%d)\n", backs[totalpro - 1].command, pid);
fflush(stdout);
}
free(copy);
}
checkprocess();
}