C - Executing Bash Commands with Execvp

I want to write a program Shellcode.c that takes in an input text file that contains bash commands separated by a new line and executes all the commands in a text file: for example, a text file will contain:

echo Hello World mkdir goofy ls 

I tried this (just to start practicing with one of the exec functions):

 #include <stdio.h> #include <unistd.h> void main() { char *name[3]; name[0] = "echo"; name[1] = "Hello World"; name[2] = NULL; execvp("/bin/sh", name); } 

I get in turn

 echo: Can't open Hello World 

I am stuck in execvp function, where did I go wrong?

+8
c bash execvp
source share
3 answers

You are doing it wrong.

The first index of the array is the name of the program, which is explained in the documents :

The functions execv (), execvp (), and execvpe () provide an array of pointers to null-terminated strings that represent a list of arguments available to the new program. The first argument, by convention, should point to the file name associated with the executable. An array of pointers must be interrupted by a NULL pointer.

In addition, bash does not expect such a free form argument, you need to say that you are going to pass commands using the -c option:

So you need to:

 name[0] = "sh"; name[1] = "-c"; name[2] = "echo hello world"; name[3] = NULL; 
+18
source share

To pass the script to bash on the command line, you must add the -c option and pass the entire script as a single line, i.e.

 #include <stdio.h> #include <unistd.h> void main() { char *name[] = { "/bin/bash", "-c", "echo 'Hello World'", NULL }; execvp(name[0], name); } 
+8
source share

There are many problems: the family of functions exec() does not execute several programs - these functions are performed by a single program and replace the current process in memory with a new program. The null-pointer string array that you pass to execvp must contain the command line arguments for the program executed by execvp .

If you want to execute several programs, you will need to iterate over each line and execute the programs one by one. But you cannot use execvp , because it immediately replaces the current executable process (your C program) with the process executed through the shell, which means that the rest of your C program will never be executed. You need to learn how to use fork() in conjunction with execvp so that you can execute child processes. First you call fork() to create the child process, and then from the child process you call execvp . Fork + Exec is a common strategy in UNIX environments to start other processes from the parent process.

+7
source share

All Articles