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

6
  • try: "/bin/bash","-c","/bin/sh" Mar 25, 2018 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; } ` Mar 25, 2018 at 11:59
  • you doubled /bin/bash Mar 25, 2018 at 13:14
  • Possible duplicate of How to use execv() without warnings?, How to use execv system call in linux?, etc.
    – jww
    Mar 25, 2018 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. Mar 25, 2018 at 20:01

1 Answer 1

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;
}
2
  • this answer is still wrong about how to handle a call to `execv()' Mar 27, 2018 at 1:53
  • regarding: return 0; in general, returning 0 indicates success. But the code was not successful. Suggest: return -1; to properly indicate the failure Mar 27, 2018 at 1:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.