Hello guys. I am working on the code below. I am trying to create my own shell. The code compiles without errors, but when I execute it though it doesn't output anything. I have tried it with /bin/ls as input and it doesn't work. Any suggestions?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv, char **envp)
{
        char line[50];
        int length = 50;
        int i = 0, j = 0, k = 0;
        system("clear");
        printf("[m_shell ] ");
        fgets(line, length, stdin);
        while(line[k] != '\0')
        {
                argv[i] = (char *)malloc(sizeof(char) * 11);
                while(line[k] != ' ')
                {
                  argv[i][j] = line[k];
                                k ++;
                                j ++;
                }
	      argv[i][j] = '\0';
                        j = 0;
                        k ++;
                        i ++;
        }
        execve(argv[0], argv, envp);
        return 0;
}

Shouldn't this end with a NULL

execve(argv[0], argv, envp, NULL);

Ooops my mistake.

You should declare your own argv, rather than trying to use the one passed in main.

Also, you'll need to make sure your last argv is NULL.

while(line[k] != '\0')
        {
                argv[i] = (char *)malloc(sizeof(char) * 11);

/*
   while(line[k] != ' ')
   This should be 
          while(line[k]!= ' '&& line[k]!='\0')
   If you give the command of the type "/bin/ls , your loop keeps on 
   searching till it find the space character
*/

                {
                  argv[i][j] = line[k];
                                k ++;
                                j ++;
                }
	      argv[i][j] = '\0';
                        j = 0;
                        k ++;
                        i ++;
        }
        execve(argv[0], argv, envp);
        return 0;
}

Also why are you using the argv array to store the parameters. Why not make a separate array ?

Problem solved :) Thank you guys for your suggestions. I really appreciate your help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.