I'm making a shell program which use execvp with a tab to execute my command.
If i put in the shell "ls -l;ls", it should exec "ls -l" (it work) then "ls" but it does "ls "
My tab will have [ls\0][-l\0], will exec perfectly
then if i try ls, my tab: [ls\0][\0] and it give me:
ls: cannot access: No such file or directory
How can I remove that last [\0] to only have [ls\0] in my tab?
Thanks
EDIT: here is the full code, can't make
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#define syserror(x) perror(errormsg[x])
#define fatalsyserror(x) syserror(x), exit(x)
#define ROUGE(m) "\033[01;31m"m"\033[0m"
#define VERT(m) "\033[01;32m"m"\033[0m"
#define FAILEDEXEC 127
#define DONTEXEC 128
#define ERR -1
#define SIZECMDLINE 4096
#define SIZE 1024
#define MAXCMD 10
#define PIPEFAILED 1
typedef struct statusProc {
int proc;
int value;
int failed;
} StatusProc;
StatusProc statusproc;
char * errormsg[] = {
"No error",
ROUGE("Impossible to fork process"),
ROUGE("Exec failed")
};
void traiterCmdInFork(char *cmd[SIZE]){
char *tab[SIZE],**ps;
int i=0;
tab[i]=cmd[i];
i++;
cmd++;
for(;*cmd && *cmd!='\0';i++,cmd++){
tab[i]=*cmd;
cmd++;
}
for (ps = tab; *ps; ps++) printf("r:%s ", *ps);
execvp(*tab, tab);
syserror(2);
exit(FAILEDEXEC);
}
int traiterInFather(char *cmd[SIZE]){
char currentdir[SIZE];
if(!strncmp(*cmd,"cd",2)){
chdir(*(cmd+1));
getcwd(currentdir, SIZE);
return 1;
} else if(!strncmp(*cmd,"status",6)){
if (!statusproc.proc){
printf("Aucune commande execute avant\n");
} else if(!statusproc.failed){
printf("%d termine avec comme code retour %d\n",statusproc.proc,statusproc.value);
} else {
printf("%d termine anormalement\n",statusproc.proc);
}
return 1;
}
return 0;
}
int main(void) {
char lgcmd[SIZECMDLINE], command[SIZE], *tabcmd[SIZE], currentdir[SIZE], *newcmd, *s, *tmp ,**ps;
pid_t p;
int i, j, nbcar, nbcmdprev, status, waitstatus, waitprev;
nbcmdprev=0;
//utiliser macro
for(;;) {
getcwd(currentdir, SIZE);
printf("%s>",currentdir);
memset(lgcmd,0,SIZECMDLINE);
fgets(lgcmd, SIZECMDLINE-1, stdin);
for(s=lgcmd; isspace(*s); s++);
s[strlen(s)-1]='\0'; //retire \n a la fin de la ligne de commande
printf("Command line:%s\n",s);
nbcar=0;
status=0;
waitprev=0;
waitstatus=0;
i=0;
newcmd=s;
printf("test");
for(;*s;s++,nbcar++){
//on avance jusqua fin dune commande
printf("R3");
if(*s==';' || *(s+1)=='\0' || *s=='|' || *s=='&'){ //traiter cas || et && et finligne
if(*s=='|' && *(s+1)=='|'){
*s++='\0';
waitprev=2;
} else if(*s=='&' && *(s+1)=='&'){
*s++='\0';
waitprev=1;
} else if(*(s+1)=='\0'){
s++;
nbcar++;
}
memset(command,0,strlen(command));
for (j = 0; j < nbcmdprev; j++) {
memset(tabcmd[j],0,strlen(tabcmd[j]));
printf("clear %d\n",j);
}
memcpy(command,newcmd,nbcar);
*s='\0';
for(tmp=command; isspace(*tmp); tmp++);
for(i=0; *tmp && tmp !=s; i++) {
tabcmd[i]=tmp;
//stopper le while quand on rencontre un ; ou & ou |
while (!isspace(*tmp) && *tmp!='\0' && *tmp!=';' && *tmp!='|' && *tmp!='&') {
printf("tmp:%c\n",*tmp);
tmp++;
}
//traiter &
if(*tmp=='|'){
waitprev=2;
*tmp++='\0';
break;
} else if(*tmp==';'){
waitprev=0;
*tmp++='\0';
break;
} else if(*tmp=='&'){
waitprev=1;
*tmp++='\0';
break;
} else if(*tmp!='\0'){
printf("tmp:%c\n",*tmp);
*tmp++='\0';
} else if(*tmp=='\0'){
printf("fin");
}
while (isspace(*tmp)) {
printf("tmp:%c\n",*tmp);
tmp++;
}
printf("tmp:%c\n",*tmp);
}
s++;
newcmd=s;
nbcar=0;
nbcmdprev=i;
if(!traiterInFather(tabcmd)){
printf("Dans if\n");
for (j = 0; j < i; j++) {
printf("len cmd%d:%d\n",j,strlen(*tabcmd));
}
p=fork();
if (p == ERR) fatalsyserror(1);
if(p) {
statusproc.proc=p;
wait(&status);
if(WIFEXITED(status)) {
if ((status=WEXITSTATUS(status)) != FAILEDEXEC) {
if(waitprev==1){
waitstatus = -1;
} else if(waitprev==2) {
waitstatus = -2;
} else {
waitstatus = 0;
}
printf(VERT("exit status of ["));
for (ps = tabcmd; *ps; ps++) printf("%s ", *ps);
printf(VERT("\b]=%d\n"), status);
//printf("\n");
statusproc.value=status;
statusproc.failed=0;
}
}
else {
statusproc.failed=1;
puts(ROUGE("Abnormal exit"));
}
} else {
printf("Command fork:");
for (ps = tabcmd; *ps; ps++) printf("-1-%s", *ps);
printf("\n" );
if((waitstatus==-1 && status==0) || (waitstatus==-2 && status!=0) ||(waitstatus==0 && status==0)){
traiterCmdInFork(tabcmd);
} else {
//stop le fils quand on ne doit pas executer commande
exit(DONTEXEC);
}
}
}
}
}
}
exit(0);
}
EDIT2: I added an int arg to traiterCmdInFork which egal the number of arg of the cmd ( ls -a = 2) so i only copy where there is text, it solved my problem.
Thanks for your help
Related
i want to make the programm loop again and again until i type the endword ****TELOS
/* 1 */ int text_input();
int main() {
int number;
text_input();
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
printf("Enter the text. (****TELOS for stoping)");
char endword[10];
strcpy(endword, "****TELOS");
char temp[N];
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I think your code doesn't work because you don't have set each item of endword to 0
so your code should be like that
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10
#define M 10
int text_input(char words[M][N]);
int main() {
char a[M][N];
text_input(a);
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
char temp[N];
char endword[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Enter the text. (****TELOS for stoping)");
strcpy(endword, "****TELOS");
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I am currently having a strange issue of dispay.
When I am running the program by doing that : t I have this result :
result of the execution of the t.exe
which is basicly the very begining of my program :
However, when I am using the gdb like that : gdb t.exe, everything works well like that : result of the execution in debug mode
Down below is my code (sorry it's not clean :/)
#include <stdio.h>
#include <stdlib.h>
typedef int typeElem;
typedef struct aa {
typeElem v ;
struct aa * fg , * fd ; // les fils gauche et droit
} abr;
#define arbre_vide NULL
typedef abr *arbre;
typedef int boolean;
arbre consa(typeElem x, arbre fils_gauche, arbre fils_droit) {
arbre N = malloc ( sizeof( arbre ) ) ;
N->fg = fils_gauche;
N->fd = fils_droit;
N->v = x;
return N;
}
void destruct(arbre ABR) {
free(ABR);
}
arbre gauche(arbre ABR) {
return ABR->fg;
}
arbre droit(arbre ABR) {
return ABR->fd;
}
int estVideArbre(arbre ABR) {
return (ABR == NULL);
}
typeElem racine(arbre ABR){
return (ABR->v);
}
/*
void destructAbr(arbre ABR){
if(!estVideArbre(ABR)){
destructAbr(gauche(ABR));
destructAbr(droit(ABR));
}
}
*/
void infixe(arbre ABR){
if(!(ABR == NULL)){
infixe(ABR->fg);
printf("%d ", ABR->v);
infixe(ABR->fd);
}
else {
//printf("est null \n");
}
}
void prefixe(arbre ABR){
if(!estVideArbre(ABR)){
printf("%d ", ABR->v);
infixe(ABR->fg);
infixe(ABR->fd);
}
}
void postfixe(arbre ABR){
if(!estVideArbre(ABR)){
infixe(gauche(ABR));
infixe(droit(ABR));
printf("%d ", racine(ABR));
}
}
int nbrTotalNoeuds(arbre ABR) {
if(estVideArbre(ABR))
return 0;
return 1 + nbrTotalNoeuds(gauche(ABR)) + nbrTotalNoeuds(droit(ABR));
}
int nbreNoeudsDe2Fils(arbre ABR) {
if( !estVideArbre(gauche(ABR)) && !estVideArbre(droit(ABR)) ){
return 1 + nbreNoeudsDe2Fils(gauche(ABR)) + nbreNoeudsDe2Fils(droit(ABR));
}
else if (!estVideArbre(gauche(ABR)) && estVideArbre(droit(ABR)) ) {
return nbreNoeudsDe2Fils(gauche(ABR));
}
else if (estVideArbre(gauche(ABR)) && !estVideArbre(droit(ABR)) ) {
return nbreNoeudsDe2Fils(droit(ABR));
}
else {
return 0;
}
}
int nbreNoeudsDe1Fils(arbre ABR) {
if( gauche(ABR) != NULL && droit(ABR) != NULL ) {
return 0 + nbreNoeudsDe1Fils(gauche(ABR)) + nbreNoeudsDe1Fils(droit(ABR));
}
else if( gauche(ABR) != NULL && droit(ABR) == NULL ) {
return 1 + nbreNoeudsDe1Fils(gauche(ABR));
}
else if( gauche(ABR) == NULL && droit(ABR) != NULL ) {
return 1 + nbreNoeudsDe1Fils(droit(ABR));
}
else {
return 0;
}
}
/*
5
/ \
3 6
/ \ \
2 4 7
\
9
*/
int main() { //test
printf("Lancement du programme \n");
arbre rac_g = consa(2,arbre_vide,arbre_vide);
arbre rac_d = consa(4,arbre_vide,arbre_vide);
arbre rac_d_d_d = consa(9,arbre_vide,arbre_vide);
arbre rac_d_d = consa(7,arbre_vide,rac_d_d_d);
arbre fg = consa(3,rac_g,rac_d);
arbre fd = consa(6,arbre_vide,rac_d_d);
arbre sommet = consa(5,fg,fd);
printf("\nEn ordre infixe : ");
infixe(sommet);
printf("\nEn ordre prefixe : ");
prefixe(sommet);
printf("\nEn ordre postfixe : ");
postfixe(sommet);
printf("\nNombre de noeuds dans cette arbre : %d\n", nbrTotalNoeuds(sommet));
printf("Nombre de noeuds a 2 fils : %d\n", nbreNoeudsDe2Fils(sommet));
printf("Nombre de noeuds a 1 fils : %d\n", nbreNoeudsDe1Fils(sommet));
// destructAbr(sommet);
return 0;
}
This
arbre N = malloc ( sizeof( arbre ) ) ;
does not do what you expect. It allocates memory for a pointer only, not for what a pointer pointed to.
Do
arbre N = malloc(sizeof *N);
instead.
I do not understand why you define three names for more or less the same thing. My advice is to drop abr and arbre, and only use struct aa and struct aa *.
Fewer names, less confusion, fewer errors.
I have been trying to write a shell in C but i keep getting e segmentation fault when running ls > test.txt (before implementing pipes it worked just fine) .
Here is the code. sorry if it is too long and not formated properly.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAX 1024
/* fonction separe donne en exercise*/
char **separe(char *chaine, const char *separateurs)
{
char **tab;
int i, s, m, size = 10;
tab = malloc(size * sizeof(char*));
m = 0;
i = 0;
while (chaine[i] != 0)
{
// saute un séparateur
for (s = 0; separateurs[s] != 0; s++)
if (chaine[i] == separateurs[s])
break;
if (separateurs[s] != 0)
{
chaine[i++] = 0; // met un fin de chaine à la place du séparateur et avance
continue; // les séparateurs n'ont pas été épuisés
}
if (chaine[i] != 0)
tab[m++] = chaine + i;
if (m == size)
{
// si j'atteinds la limite de la taille de mon tableau, je l'agrandis.
size += 10;
tab = realloc(tab, size * sizeof(char*));
}
// saute les caractères non séparateurs
for (; chaine[i] != 0; i++)
{
for (s = 0; separateurs[s] != 0; s++)
if (chaine[i] == separateurs[s])
break;
if (separateurs[s] != 0)
break; // trouvé un caractère séparateur, j'arrête d'avancer et je passe au mot suivant
}
}
tab[m] = NULL;
return(tab);
}
void decaler2gauche(char ** tab, int pos)
{
int i = pos;
while( tab[i+2] != NULL )
{
tab[i] = tab[i+2];
i++;
}
tab[i] = NULL;
}
char** pipetest( char **arg) {
int sizeTab = 0;
int k,j;
char **newtab;
for (k = 0; arg[k] != NULL; k++)
{
sizeTab++;
}
int i =0;
while( arg[i] != NULL )
{
if( strncmp(arg[i],"|",1) == 0 )
{
for (j=0;j < i ; j++){
newtab[i] = arg[i];
}
break;
}
i++;
}
newtab[i] = NULL;
return newtab;
}
char** pipetest2( char **arg) {
int sizeTab = 0;
int k , j;
char **newtab;
for (k = 0; arg[k] != NULL; k++)
{
sizeTab++;
}
int i =0;
while( arg[i] != NULL )
{
if( strncmp(arg[i],"|",1) == 0 )
{
for ( j= i+1 ; j < sizeTab ; j++ ) {
newtab[j] = arg[j];
}
break;
}
i++;
}
newtab[sizeTab] = NULL;
return newtab;
}
/* la fonction main*/
int main(int argc, char *argv[]) {
char cmd[MAX];
char **commande; //ici on met la commande
char *newcommande[MAX]; // ici on met la commande apres avoir verifie le contenu de commande
int i, j, k,t,a, fd, fd2, raison ; // les variables utilise
char *tmp, *new_path , *new_path1 , *new_path2;
char *ge_path, *path, **tab;
int test;
int status , status2; // la variable test pour le access
char **commande1;
char **commande2;
pid_t pid , pid2;
// récupère la valeur de $PATH
ge_path = getenv("PATH");
// crée une copie locale modifiable
// (on ne doit pas modifier la zone mémoire renvoyée par getenv)
path = malloc(strlen(ge_path) + 1);
strcpy(path, ge_path);
tab = separe(path, ":");
while (1) {
int copy = 0;
int paste = 0;
int piping = 0;
int fdout;
int fdin;
int tabfd[2];
printf("myshell > ");
fgets(cmd, MAX, stdin);
commande = separe(cmd, " \n");
/* Cette boucle verifie si la commande passe en parametre est dans le PAth ou pas*/
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path = tmp;
break;
}
}
char* fileNameIn;
char* fileNameOut;
for (j = 0; commande[j] != NULL; j++)
{
if (strcmp(commande[j], ">") == 0) //out
{
fileNameOut = commande[j + 1];
fdout = open(fileNameOut, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fdout == -1)
{
perror("open\n");
exit(1);
}
decaler2gauche(commande,j);
copy = 1;
}
if (strcmp(commande[j], "<") == 0) //in
{
fileNameIn = commande[j + 1];
printf("%s\n", fileNameIn);
fdin = open(fileNameIn, O_RDONLY);
if (fdin == -1)
{
perror("open\n");
exit(1);
}
paste = 1;
decaler2gauche(commande,j);
}
if (strcmp(commande[j], "|") == 0) // pipe {
{
piping = 1;
}
newcommande[j] = commande[j];
}
if (piping) {
commande1=pipetest(newcommande);
commande2=pipetest2(newcommande);
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande1[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path1 = tmp;
break;
}
}
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande2[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path2 = tmp;
break;
}
}
pipe(tabfd);
switch (pid=fork()) {
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
close(1);
dup(tabfd[1]);
if (paste)
{
if (dup2(fdin, 0) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
if (copy)
{
if (dup2(fdout, 1) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
execv(new_path1, commande1);
perror("cmd");
exit(1);
default :
wait(&status2);
break;
}
switch (pid2=fork()) {
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
close(0);
dup(tabfd[0]);
if (paste)
{
if (dup2(fdin, 0) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
if (copy)
{
if (dup2(fdout, 1) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
execv(new_path2, commande2);
perror("cmd");
exit(1);
default :
wait(&status);
break;
}
close(tabfd[0]);
close(tabfd[1]);
}
else {
switch (pid = fork())
{
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
if (paste)
{
if (dup2(fdin, STDIN_FILENO) == -1)
{
perror("dup2 fdin \n");
exit(1);
};
}
if (copy)
{
if (dup2(fdout, STDOUT_FILENO) == -1)
{
perror("dup2 fdin \n");
exit(1);
};
}
execv(new_path, commande);
perror("cmd");
exit(1);
default:
wait(&status);
break ;
}
}
free(commande);
free(tmp);
}
free(tab);
//free(commande);
free(path);
free(new_path);
exit(0);
}
I am currently writing a shell for school purposes and I have the problem that if I write the command "history", the "exit" command afterwards doesn't work. If you could help me I would be very happy.
Here is my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#define MAX_INPUT 256
static char cwd[100];
void myprintf(char *text) {
text != NULL ?
printf("%s#rash:%s: %s\n", getenv("USER"), getcwd(cwd, sizeof(cwd)), text) :
printf("%s#rash:%s: ", getenv("USER"), getcwd(cwd, sizeof(cwd)));
}
void errprintf(char *text) {
myprintf(NULL);
printf("Couldn't run %s\n", text);
}
static char *argv[256];
static int argc;
static int pid = 0;
FILE *fhistory;
void parseInput(char *input) {
input = strtok(input, "\n");
for (argc = 0; argc < MAX_INPUT; argc++) {
argv[argc] = NULL;
}
argc = 0;
fprintf(fhistory, "%s\n", input);
char *param = strtok(input, " ");
while (param) {
argv[argc++] = param;
param = strtok(NULL, " ");
}
}
void signalHandler(int sign) {
switch (sign) {
case SIGINT: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
case SIGCHLD: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
}
}
int programs() {
if (!strcmp(argv[0], "exit")) {
return -1;
}
if (!strcmp(argv[0], "cd")) {
chdir(argv[1] == NULL ? getenv("HOME") : argv[1]);
} else {
pid = fork();
switch (pid) {
case -1: {
myprintf("Erectile Dysfunction!");
break;
}
case 0: {
if (!strcmp(argv[0], "history")) {
system("cat .rash_history.txt");
} else {
execvp(argv[0], argv);
errprintf(argv[0]);
}
break;
}
default: {
waitpid(pid, NULL, 0);
signal(SIGCHLD, signalHandler);
return 0;
}
}
}
return 1;
}
int main(void) {
signal(SIGINT, signalHandler);
char *input = NULL;
myprintf("Welcome to rash!");
fhistory = fopen(".rash_history.txt", "a");
while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
myprintf(NULL);
input = (char *) malloc(sizeof(char *) * MAX_INPUT);
int j;
for (j = 0; j < MAX_INPUT; j++) {
input[j] = '\0';
}
fgets(input, MAX_INPUT, stdin);
parseInput(input);
if (*(input) != '\n') {
programs();
}
}
fclose(fhistory);
return 0;
}
I think here while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
it would be strlen("exit")
The "input" variable take value inside your while loop only:
fgets(input, MAX_INPUT, stdin);
parseInput(input);
The parseInput uses strtok function couple times. The strtok modifies the argument string, so it not clear what value it will contains at time you will compare it with "exit".
Try to duplicate "input" string before calling strtok. Try to add debug string at the end of loop to make clear what value is into input string.
How can i check if i am using right the dynamic allocation in my C code.
It is an assignment for uni. When i put my code in the auto corrector system of my professor i get an error for dynamic allocation. My code :
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include <ctype.h>
int main( )
{
for(;;)
{
char *cmd,*splitcmd;
//*pr0,*pr1,*pr2 ;
size_t bufsize = 1024;
char pr1[bufsize];
char pr2[bufsize];
char pr0[bufsize];
//char pr3[40];
int i,j,nargc=0,characters;
char **cmdArray;
//size_t bufsize = 1024;
// size_t bufsizecmd =1024;
pid_t pid,wpid;
int status = 0;
char pr='$';
char exit1[10]="exit";
char *path;
path = getenv("PATH");
putchar(pr);
cmd = malloc(bufsize * sizeof*cmd);
characters = getline(&cmd,&bufsize,stdin);
//printf("cmd===> %s characters===> %d \n",cmd,characters);
if(cmd[characters-1]=='\n' )
{
cmd[characters-1]='\0';
characters--;
}
//printf("cmd===> %s characters===> %d \n",cmd,characters);
cmdArray = malloc(bufsize*sizeof*cmdArray );
for ( i = 0; i < bufsize; i++ )
{
cmdArray[i]=malloc(bufsize*sizeof*cmdArray );
}
splitcmd=strtok(cmd," ");
// printf(" cmd==== %s\n",cmd);
while((splitcmd))
{
strcpy(cmdArray[nargc],splitcmd);
if(cmdArray[nargc][(strlen(cmdArray[nargc]))-1]==' ')
cmdArray[nargc][(strlen(cmdArray[nargc]))-1]='\0';
//printf(" nargc====%d cmdArray===[%s] \n",nargc,cmdArray[nargc]);
nargc++;
splitcmd = strtok(NULL," ");
}
//printf(" pr0 %s \n",pr0);
//printf(" pr1 %s \n",pr1);
//printf(" pr2 %s \n",pr2);
strcpy(pr0,cmdArray[0]);
if (strcmp( pr0, exit1) == 0 )
{
//printf("---------->Eksodos apo to programma<---------- \n");
free(cmd);
return (0);
exit(0);
//return (0);
}
else
{
if ((pid=fork()) == 0)
{
if(nargc ==1 )
{
strcpy(pr0,cmdArray[0]);
char *argv[] = {path,NULL};
execvp(pr0,argv);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
else if(nargc==2)
{
strcpy(pr0,cmdArray[0]);
strcpy(pr1,cmdArray[1]);
char *argv[] = {pr0,pr1,NULL};
execvp(pr0,argv);
exit(0);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
else
{
strcpy(pr0,cmdArray[0]);
strcpy(pr1,cmdArray[1]);
strcpy(pr2,cmdArray[2]);
//printf("cmdddddddd****====%s \n",*cmdArray);
char *argv[] = {pr0,pr1,pr2,NULL};
execvp(argv[0],argv);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
}
wait(&status);
}
}
}
There is no corresponding free() for cmd = (char *)malloc(bufsize * sizeof(char));.
Also, this code block:
strcpy(pr0,cmdArray[0]);
if (strcmp( pr0, exit1) == 0 )
{
//printf("---------->Eksodos apo to programma<---------- \n");
free(cmd);
return (0);
exit(0);
//return (0);
}
will need this
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
before the
free(cmd);
In this code block, there are two exit() calls:
else if(nargc==2)
{
strcpy(pr0,cmdArray[0]);
strcpy(pr1,cmdArray[1]);
char *argv[] = {pr0,pr1,NULL};
execvp(pr0,argv);
exit(0);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
The one immediately after the execvp(pr0,argv); prevents any of the free() calls from being executed. It needs to be removed.