-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_bg.c
More file actions
60 lines (57 loc) · 1016 Bytes
/
cmd_bg.c
File metadata and controls
60 lines (57 loc) · 1016 Bytes
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
void addbg(int pidx)
{
idx++;
numproc++;
pidarr[idx]=pidx;
pidctr[idx]=idx;
strcpy(pidcmd[idx],s_save);
// printf("%d %d %s\n", idx,pidarr[idx],pidcmd[idx]);
}
void cmd_bg()
{
if(strstr(s,"&"))
{
strtok(s,"&");
char * tok = strtok(s," ");
char *args[100]={};
int i=0;
while(tok!=NULL)
{
args[i++]=tok;
tok = strtok(0," ");
}
int status,st=0;
pid_t pid = fork(),sid;
int final_in = dup(0),final_out = dup(1);
if (pid == -1)
{
printf("can't fork, error occured\n");
exit(EXIT_FAILURE);
}
else if(pid > 0) {
addbg(pid);
waitpid(-1, &status, WNOHANG);
dup2(final_in,0);
dup2(final_in,1);
stx=1;
}
else
{
stx=1;
printf("%d.[%d] - [%s]\n",idx+1,getpid(),s_save);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
int x = open("/dev/null", O_RDWR);
dup(x);
dup(x);
if(execvp(args[0],args)<0) {
dup2(final_in,0);
dup2(final_in,1);
perror(args[0]);
}
exit(1);
}
}
strcpy(s,s_save);
}