1

i am trying to perform the command sh that start a new terminal in Linux from a c program, but i get this error /bin/sh: /bin/sh: cannot execute binary file when i am using execv ()and same result with fork and then execv. but when i tried it system command a succeed , how can i do this command with execv?

work's :

int main (){
        system("sh");
        return 0;
}

does'nt work :

int main (){

        int ret=0;
        char *argv[] = {"/bin/bash", "/bin/sh",NULL};
        ret=execv(argv[0], argv);

        printf("ret: %d \n",ret);
        return 0;
}

this code return this error : /bin/sh: /bin/sh: cannot execute binary file

Omer Anisfeld
  • 1,236
  • 12
  • 28
  • try: ```"/bin/bash","-c","/bin/sh"``` – Marcin Fabrykowski Mar 25 '18 at 11:54
  • same error when i try this : ` int main (){ int ret=0; char *argv[] = {"/bin/bash", "/bin/bash","-c","/bin/sh",NULL}; ret=execv(argv[0], argv); return 0; } ` – Omer Anisfeld Mar 25 '18 at 11:59
  • you doubled ```/bin/bash``` – Marcin Fabrykowski Mar 25 '18 at 13:14
  • Possible duplicate of [How to use execv() without warnings?](https://stackoverflow.com/q/10790719/608639), [How to use execv system call in linux?](https://stackoverflow.com/q/32142164/608639), etc. – jww Mar 25 '18 at 18:32
  • 1
    The reason the original is failing is because it's the equivalent of running the command `/bin/bash /bin/sh`, and if you run that at the command line you'll get the exact same error. The reason is that by default, /bin/bash interprets its first argument *as a shell script file* to be executed, and /bin/sh is not a shell script, it's a binary. – Gordon Davisson Mar 25 '18 at 20:01
  • All the `exec...()` functions ONLY return IF they fail. so the only statements to follow a call to one of those functions (no need to put it in a `if()` statement) are: `perror( "exec...() failed" ); exit( EXIT_FAILURE );` – user3629249 Mar 27 '18 at 01:51

1 Answers1

2
cat aa.c

#include<stdio.h>
#include<unistd.h>
int main (){

        int ret=0;
        char *argv[] = {"/bin/bash", "-c","/bin/sh",'\0'};
        ret=execv(argv[0], argv);

        printf("ret: %d \n",ret);
        return 0;
}

gcc aa.c -o aa

./aa 
sh-4.4$ 

and... what about just:

#include<stdio.h>
#include<unistd.h>
int main (){

    int ret=0;
    char *argv[] = {"/bin/sh",'\0'};
    ret=execv(argv[0], argv);

    printf("ret: %d \n",ret);
    return 0;
}