forked from pinbraerts/3_sem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTask1.c
56 lines (46 loc) · 1.65 KB
/
Task1.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
#include <unistd.h> //fork
#include <stdio.h> //printf fgets stdin
#include <string.h> //strcmp strtok strlen
#include <stdlib.h> //malloc
#include <sys/wait.h> //waitpid WEXITSTATUS
int main() {
int arg_max = sysconf(_SC_ARG_MAX); //get the maximum possible length of a command
char* cmd = malloc(arg_max); //allocate memory for the command
while(1) {
printf("Enter command: ");
int cmdlen = strlen(fgets(cmd, arg_max, stdin));
if(!strcmp(cmd, "exit"))
return 0;
if(strspn(cmd, " ") == strlen(cmd)) { //ignore commands consisting only of spaces
printf("Incorrect command\n");
continue;
}
int c_pid = fork(); //fork into two
int status = c_pid;
if(c_pid == 0) { //act as child
int argc = (cmd[0] != ' ');
for(int i = 0; cmd[i]; i++)
if(cmd[i] == ' ' && cmd[i+1] != ' ' && cmd[i+1] != 0)
argc++;
char** argv = malloc(argc * sizeof(char*)); //allocate memory for arguments
char* name = strtok(cmd, " ");
argv[0] = name;
for(int i = 1; i < argc; i++)
argv[i] = strtok(NULL," ");
execvp(
name,
argv
);
return 42;
}
else { //act as parent
waitpid(c_pid, &status, 0);
status = WEXITSTATUS(status);
}
if(status == 42)
printf("Incorrect command\n");
else
printf("Exit status: %d\n", status);
}
return 0;
}