简体   繁体   中英

Call mkdir syscall with execve in C

I am very new to C and am in an OS class where I need to write a basic shell in C (yay). It's actually been going halfway decently, I am just trying to learn C basics while getting through the work.

I am trying to use exec after forking and call, for now, mkdir. The arguments required through me off a little, but I've been trying to figure it out and was hoping someone could tell me where I've gone wrong.

            } else {
            //fork exec
            int pid = fork();
            if (pid == 0) {
                printf("%s",my_argv[0]);
                execve("/bin/mkdir",my_argv,0);
            } else wait(NULL);
        }

This is the portion where I am responding to the mkdir call. Right now, I have a line[] that is input from the user, the command is taken with

command = strtok(line, DELIMITERS);

The arg is :

arg = strtok(0,DELIMITERS);
        my_argv[0] = arg;

Everything compiles fine but the mkdir never works. Printing my_argv[0] gives the correct argument that I expect. I'm sure this is something stupid but any tips would be appreciated.

All Code:

int main(int argc, char *argv[])
{
char *command;
char line[MAXLINE];
char *arg = NULL;
char *my_argv[]; 


while(1) {
    printf(PROMPT);
    if (fgets(line,MAXLINE,stdin) != NULL) {
        //take out \n
        line[strlen(line)-1] = '\0';
    }
    //looks for first delimiter, saves as the command
    command = strtok(line, DELIMITERS);


    //start looking at what command it is by comparing
    if (strcmp(command,"cd")==0) {
        //if they equal zero, they match
        //this is a cd command, must have following arg
        if (argv[1] == NULL) chdir("/");
        else chdir(argv[1]);//chdir is the system call for cd
    } else if (strcmp(command,"exit")==0) {
        break;
    } else if (strcmp(command,"mkdir")==0){
        arg = strtok(0,DELIMITERS);
        my_argv[0] = arg;
        my_argv[1] = NULL;
        if (!arg) {
            printf("Usage: mkdir missing arg\n");
        } else {
            //fork exec
            int pid = fork();
            if (pid == 0) {
                printf("%s",my_argv[0]);
                //mkdir(arg);
                             execve("/bin/mkdir",my_argv,0);
            } else wait(NULL);
        }
    }


}
return 0;
}
  • argv[0] contains the name of the program
  • argv[1] is the first argument
  • argument list must be NULL terminated

您可以使用mkdir系统调用而不是execve

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM