-2

I´m trying to run the following code, but it doesn´t work. I just want to execute a program, when the input name of the programm is done. I don´t know where the problem really is, cauze the code seems ok. Maybe there are other important things, that I did not notice...

setbuf(stdout, NULL);
char input[255];
char path[255];
int status;
char *args[2] = {"ls", NULL};             
while(strcmp(input, "end") != 0 ){
    printf("Waiting for input:\n");
    scanf("%s",input);
    strcpy(path, "./");
    strcat(path, input);
    if(strcmp(input, "end") != 0){
        printf("execute %s\n", path);
        int ret = execv(path, args);
        if(ret == -1){
            perror("execve error");
        } 
    }
    else{
        printf("Programm-Ends\n");
    }    
};    
return 0;
Barmar
  • 741,623
  • 53
  • 500
  • 612
Bibi90
  • 1
  • 2
  • 1
    a) Make an [mcve] b) elaborate "does not work" c) describe the result of your debugging attempts d) as a lucky charm, get the badge for taking the [tour] – Yunnosch Jan 23 '18 at 07:24
  • Tips for debugging: a) What is the return value of scanf() b) what does that value mean d) https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ e) https://stackoverflow.com/questions/2069367/how-to-debug-using-gdb f) https://ericlippert.com/2014/03/21/find-a-simpler-problem/ – Yunnosch Jan 23 '18 at 07:28
  • Tips for avoiding downvotes: a) delete the question b) edit the question (see my other comments) c) when you have more info and an improved question, undelete it – Yunnosch Jan 23 '18 at 07:29
  • Sooner or later your negative scored questions will get you in trouble (https://stackoverflow.com/help/question-bans). Take the advice to clean them up. – Yunnosch Jan 23 '18 at 07:31
  • You're not initializing the `input` before `strcmp`, therefore your program has undefined behaviour. – Antti Haapala -- Слава Україні Jan 23 '18 at 07:31
  • If `execv()` is successful, it never return, because it replaces the current process with that program. So your loop won't repeat. If you want the original program to keep running, you need to fork a child and use `execv()` there. – Barmar Jan 23 '18 at 08:04
  • 1
    `args[0]` should usually be the name of the program. You shouldn't hard-code it to `ls`. – Barmar Jan 23 '18 at 08:05
  • Thanks a lot for your answer @Barmar! Thats exactly what I wanted. – Bibi90 Jan 23 '18 at 11:37

1 Answers1

0

The first element of args should be the name of the program being run. So put:

args[0] = path;

before the call to execv().

Barmar
  • 741,623
  • 53
  • 500
  • 612