Run the TOP command in exec on C - Linux?

Asked

Viewed 288 times

0

Updated code ,it does not execute commands

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



void ExeclLS(int argc, char **argv)  {
    char *args[] = {"ls", "-aF", "/", 0};
    char *env[] = { 0 };

    printf("Rodando o bin/ls\n");
    execve("bin/ls", args, env);
}

void ExeclTop(int argc, char **argv) {
    char *args[] = {"top", "-aF", "/", 0};
    char *env[] = { 0 };

    printf("Rodando o bin/top\n");
    execve("/usr/bin/top", args, env);
}

int main() {

    int valorMenu;

    printf("Digite o comando : 1 - ls , 2-top\n");
    scanf("%i",&valorMenu);

    if (valorMenu == 1){
    printf("Rodando o bin/ls\n");
    ExeclLS(0, NULL);

    }else{
    printf("Rodando o bin/Top\n");
    ExeclTop(0,NULL);

    }

        perror("execve");   
        exit(1);
    return 0;
 }

Someone can help me?

  • The perror() gives some interesting error message?

  • This code runs normally, but when I put "/bin/top" it prints "execve" and then no file found

  • 1

    So ... this means that the "top" is not in the "/bin" directory. It does whereis top to try to find out where he is.

  • Thank you! You helped me so much

  • Your structure of if / if / else is not well organized. The else only concerns the second if.

  • I updated the code there

  • foul / in execve("bin/ls", args, env); ==> execve("/bin/ls", args, env);

Show 2 more comments

2 answers

3

In the snippet

    if (valorMenu == 1) {
        printf("Rodando o bin/ls\n");
        void ExeclLS(int argc, char **argv);    // <== ATENÇÃO
    }

the line with the reminder "does nothing". It is just a statement.

To run the write function, for example

        ExeclLS(0, NULL);
  • I put the argument and nothing :/ "Running bin/ls Running bin/top No found command execve: No such file or directory"

2

The message of perror()

/bin/top: no file found

indicates that the top is not in the directory /bin.
At the command line, do whereis top to find out where the program in question is.

$ whereis top
top: /usr/bin/top

In this case the top is on the board /usr/bin.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.