-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecute.c
120 lines (116 loc) · 2.62 KB
/
execute.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
#include<stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include<unistd.h>
#include<string.h>
#include <dirent.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<time.h>
#include<grp.h>
#include <sys/wait.h>
#include<fcntl.h>
#include "cd.h"
#include "command.h"
#include "display.h"
#include "echo.h"
#include "execute.h"
#include "ls.h"
#include "nightswatch.h"
#include "pinfo.h"
#include "pwd.h"
#include "redirection.h"
#include "jobs.h"
#include "global.h"
#include "global.c"
//handler for printing when a background process exits.
void childhandler(int signum)
{
pid_t childpid;
int status;
while ((childpid = waitpid( -1, &status, WNOHANG)) > 0)
{
RemoveJob(childpid);
if (WIFEXITED(status)) {
printf("\nChild process with pid %d exited normally\n", childpid);
}
if (WIFSIGNALED(status)) {
printf("\nChild process with pid %d exited because of signal\n", childpid);
}
}
return;
}
// This function is to execute backgroung and foreground commands
int ExecuteOtherCommands(char *token,const char delemiter[])
{
char *argv[10000];
int top = 0;
int flag = 0;
int pid;
int pid1,val;
int k;
int status;
int cpid;
while(token != NULL)
{
argv[top++] = token;
token = strtok(NULL,delemiter);
if(token == NULL && strcmp(argv[top-1],"&") == 0)
{
flag = 1;
}
}
argv[top] = NULL;
if(flag == 0)
{
pid = fork();
if(pid == 0)
{
k = execvp(argv[0],argv);
if(k<0)
{
fprintf(stderr,"Invalid command\n");
}
exit(0);
}
else
{
// wait(NULL);
do
{
cpid = waitpid(pid,&status,WUNTRACED);
} while(!WIFEXITED(status) && !WIFSIGNALED(status) && !WIFSTOPPED(status));
return 0;
}
}
else
{
argv[top-1] = NULL;
pid = fork();
if(pid == 0)
{
if(strcmp(argv[0],"cd") == 0)
{
usecommand[strchr(usecommand,'&')-usecommand] = ' ';
token = strtok(usecommand,delemiter);
ExecuteCD(token,delemiter);
}
else
{
k = execvp(argv[0],argv);
if(k<0)
{
fprintf(stderr,"Invalid Command\n");
}
}
exit(0);
}
else
{
AddJob(pid);
signal(SIGCHLD, childhandler);
printf("%d\n",pid);
return 0;
}
}
}