0
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
void type_prompt(){
printf("\n$~");
}
void read_command(char command[], char *parameters[]){
char linha[100] = "";
fgets(linha, 100, stdin);
int i;
int flag = 0;
for (i = 0; i <= strlen(linha); i++){
if (linha[i] == ' '){
flag = 1;
break;
}
}
char *word = strtok(linha, " ");
strcat(command, "/bin/");
strcat(command, word);
parameters[0] = word;
if (flag == 1) command[strlen(command)] = '\0';
else command[strlen(command) - 1] = '\0';
if (flag == 1){
while (word != NULL){
word = strtok(NULL, " ");
strcat(*parameters, word);
}
}
}
int main (){
char command[] = {""};
char *parameters[100] = {NULL}; //argv
char *env[]={"PATH=/usr/local/sbin/:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games",NULL};
int status;
while (1){
type_prompt();
read_command(command, parameters);
if (fork() != 0){
command[0] = '\0';
parameters[0] = '\0';
waitpid(-1, &status, 0);
}
else {
execve(command, parameters, env);
command[0] = '\0';
parameters[0] = '\0';
printf("Erro execve %d: %s\n", errno, strerror(errno));
}
}
}
Describe your error better and point out exactly the relevant code snippet to the problem.
– Leandro Angelo
The purpose of the code is to simulate a shell. However, I believe the problem lies in the read_command function. Because commands without spaces work normally, such as "ps", but when placing "ps aux", there is a segmentation error.
– Samuel Santiago