Im confused of the use of the systemcall execve.
The second parameter should be a pointer to the arguments but it doesnt work, it does however execute correctly when I send the whole command(/bin/bash) + arg as a second parameter.
./test /bin/bash "echo 'this is a test' | wc -c"
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
execve(argv[1], &argv[1], NULL); ////works, but I dont understand how since the 2nd param is wrong.
return 0;
}
int main(int argc, char *argv[]) {
execve(argv[1], &argv[2], NULL); ////doenst work, it should since Im sending the correct aguments.
printf("hi");
return 0;
}
argv[0] contains the name of the file being executed. Therefore, execve also needs the file being executed as first element (index 0).
From the execve(2) man page:
argv is an array of pointers to strings passed to the new program
as its command-line arguments. By convention, the first of these
strings (i.e., argv[0]) should contain the filename associated
with the file being executed. The argv array must be terminated
by a NULL pointer. (Thus, in the new program, argv[argc] will be
NULL.)
In other words, the arguments list that you pass in the second parameter includes the name of the executable itself (even though that is already specified in the first parameter). This is how executables are able to detect how they're being invoked (e.g. through a symlink) and show the correct name in their "help" output.
In execve man we can see that its prototype is:
int execve(const char *pathname, char *const argv[], char *const envp[]);
According to execve man (https://man7.org/linux/man-pages/man2/execve.2.html)
argv is an array of pointers to strings passed to the new program
as its command-line arguments. By convention, the first of these
strings (i.e., argv[0]) should contain the filename associated
with the file being executed. The argv array must be terminated
by a NULL pointer. (Thus, in the new program, argv[argc] will be
NULL.)
In respect to these rules you're code should be:
#include <stdio.h>
#include <unistd.h>
int main ()
{
char *filepath = "/bin/echo";
char *argv[] = { filepath, "Hello World", NULL };
execve (filepath, argv, NULL);
return 0;
}
execve call executes a program from the caller. Just as any program in C, it requires argv[0] to be set to the name of the executable being executed. This is generally done automatically when executing from command line, but since you're using execve you have to do it yourself.
If argv_1[1] = <executable path for program_2>, when you call program_2 from program_1 with execve(argv_1[1], &argv_1[1], NULL), program_2 recieves an argv array such that argv_2[0] = argv_1[1], argv_2[1] = argv_1[2], and so on.
Notice how your second main does not follow this rule.
Related
I've just recently been exploring the execve() system function. This code might not make much sense but that's not the main focus of this question. (I've managed to make it work correctly since, using this thread).
I've come across a really weird behavior and wanted either an explanation or a confirmation that something like this should not happen.
The "bugged" code is this:
#include <unistd.h>
int main(int argc, char **argv, char **env)
{
if (argc != 2)
return (ERROR_CODE);
char *test[] = { argv[1] };
char *a[] = { NULL };
execve(argv[1], test, env);
return (SUCCESS_CODE);
}
Compiling and executing it with an argument will correctly execute that function, in my case:
$> gcc main.c
$> ./a.out "/bin/ls"
This would work like the ls function would.
Now remove/comment this line:
char *a[] = { NULL };
This variable is clearly not used and completely useless.
Do the same steps once again and for some reason, it doesn't output anything, this one random variable breaks the code for me. (I'm running Ubuntu 20.04 with Gnome 3.36.8 and gcc 9.3.0).
If you need any more information about my OS or anything, feel free to ask.
PS: I think I understand the way the code is trying to work this out but It makes no sense to me.
$> man execve
main(int argc, char *argv[])
char *newargv[] = { NULL, "hello", "world", NULL };
...
execve(argv[1], newargv, newenviron);
The manual example null-terminates "newargv", my idea is that somehow, somewhere, the compiler decided to fuse together my variables "test" and "a", to null-terminate "test"?
Yep, you're accidentally seeing that "fusing" since you're not correctly terminating argv with a NULL and the memory layout happens to be in your favor. If you were less lucky, you'd get garbage in there, or a segfault.
Quoth the manpage (Linux, Darwin), emphasis mine,
The argument argv is a pointer to a null-terminated array of character pointers to null-terminated character strings.
#include <unistd.h>
int main(int argc, char **argv, char **env)
{
if (argc != 2)
return (ERROR_CODE);
char *test[] = { argv[1], NULL };
execve(argv[1], test, env);
return (SUCCESS_CODE);
}
would be the correct invocation.
I have a python script script.py which takes command line params
I want to make a wrapper in C so I can call the script.py using ./script args
So far I have this in my script.c file
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
system("python3.4 script.py");
return 0;
}
How do I modify the script so I can do ./script arg1 arg2 and the C code executes system("python3.4 script.py arg1 arg2");
I don't have experience in C. Above code is from googling
Using system() is needlessly complicated in this case, as it effectively passes the given command string to (forked) sh -c <command>. This means that you'd have to handle possible quoting of arguments etc. when forming the command string:
% sh -c 'ls asdf asdf'
ls: cannot access 'asdf': No such file or directory
ls: cannot access 'asdf': No such file or directory
% sh -c 'ls "asdf asdf"'
ls: cannot access 'asdf asdf': No such file or directory
Note the difference between the unquoted and quoted versions.
I'd suggest using execve(), if executing the python command is the only purpose of your C program, as the exec family of functions do not return on success. It takes an array of const pointers to char as the new argv, which makes handling arguments easier:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PYTHON "/usr/bin/python3"
#define SCRIPT "script.py"
int
main(int argc, char *argv[])
{
/* Reserve enough space for "python3", "script.py", argv[1..] copies
* and a terminating NULL, 1 + 1 + (argc - 1) + 1 */
int newargvsize = argc + 2;
/* VLA could be used here as well. */
char **newargv = malloc(newargvsize * sizeof(*newargv));
char *newenv[] = { NULL };
newargv[0] = PYTHON;
newargv[1] = SCRIPT;
/* execve requires a NULL terminated argv */
newargv[newargvsize - 1] = NULL;
/* Copy over argv[1..] */
memcpy(&newargv[2], &argv[1], (argc - 1) * sizeof(*newargv));
/* execve does not return on success */
execve(PYTHON, newargv, newenv);
perror("execve");
exit(EXIT_FAILURE);
}
As pointed out by others, you should use the official APIs for this, if at all possible.
You can generate your command as a string. You just need to loop through argv[] to append each parameters given to the C program at then end of your command string. Then you can use your command string as the argument for the system() function.
I have the following piece of C code that is being called with arguments:
int main(int argc, char *argv[])
{
system( "/home/user/script.sh" );
return 0;
}
how do i pass all arguments received down to script.sh?
You could synthesize some string (escaping naughty characters like quote or space when needed, like Shell related utility functions of Glib do) for system(3).
But (on Linux and Posix) you really want to call execv(3) without using system(3)
You may want to read (in addition of the man page I linked above) : Advanced Linux Programming
I think that you are looking for the execv function. It will grant to you to execute a specific file passing to it some optional arguments.
Try something next:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
system("cat /etc/passwd");
extern char * const environ[];
char * const command[] = {"mylsname", "-lR", "/", NULL};
execve("/bin/ls", command, environ);
perror("execve");
exit(EXIT_FAILURE);
}
You can use snprintf() function to frame a string. For example, snprintf(filename, sizeof(char) * 64, "/home/user/script.sh %s", argv[1]); and use system(filename);
I am trying to spawn a new process using execve() from unistd.h on Linux. I have tried passing it the following parameters execve("/bin/ls", "/bin/ls", NULL); but get no result. I do not get an error either, the program just exits. Is there a reason why this is happening? I have tried launching it as root and regular user. The reason I need to use execve() is because I am trying to get it to work in an assembly call like so
program: db "/bin/ls",0
mov eax, 0xb
mov ebx, program
mov ecx, program
mov edx, 0
int 0x80
Thank you!
The arguments that you're passing to execve are wrong. Both the second and third must be an array of char pointers with a NULL sentinel value, not a single pointer.
In other words, something like:
#include <unistd.h>
int main (void) {
char * const argv[] = {"/bin/ls", NULL};
char * const envp[] = {NULL};
int rc = execve ("/bin/ls", argv, envp);
return rc;
}
When I run that, I do indeed get a list of the files in the current directory.
From the man pages,
int execve(const char *filename, char *const argv[], char *const envp[]);
So the problem in your case is that you haven't passed the 2nd and the 3rd argument correctly.
/* execve.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
char *newargv[] = { NULL, "hello", "world", NULL };
char *newenviron[] = { NULL };
newargv[0] = argv[1];
execve(argv[1], newargv, newenviron);
}
//This is a over-simplified version of the example in the man page
Run this as:
$ cc execve.c -o execve
$ ./execve ls
Try reading man execve again. You are passing the wrong arguments to it. Pay particular attention to what the second argument should be.
Also, running your program under strace could be illuminating.
I have made little program for computing pi (π) as an integral. Now I am facing a question how to extend it to compute an integral, which will be given as an extra parameter when starting an application. How do I deal with such a parameter in a program?
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main are:
int argc - the number of arguments passed into your program when it was run. It is at least 1.
char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.
Basic Example
For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.
[birryree#lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree#lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
A Simple Case for You
And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Better command line parsing
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project.
http://tclap.sourceforge.net/
A similar library is available for C as well.
http://argtable.sourceforge.net/
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.