Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call execl() in C with the proper arguments?

i have vlc (program to reproduce videos) if i type in a shell:

/home/vlc "/home/my movies/the movie i want to see.mkv"

it opens up an reproduces the movie.

however, when I run the following program:

#include <unistd.h>

int main(void) {

  execl("/home/vlc", "/home/my movies/the movie i want to see.mkv",NULL);

  return 0;
}

vlc opens up but doesn't reproduce anything. How can I solve this?

Things I tried:

I guessed

execl("/home/vlc", "/home/my movies/the movie i want to see.mkv",NULL);

was equivalent to typing in the shell:

/home/vlc /home/my movies/the movie i want to see.mkv

which doesn't work, so i tried

 execl("/home/vlc", "\"/home/my movies/the movie i want to see.mkv\"",NULL);

and vlc opens up but doesn't reproduce either.

Instead of writing NULL at the end I tried 0, (char*) 0, 1 .... not helpful. Help!!!!

like image 309
Matias Morant Avatar asked Sep 26 '12 07:09

Matias Morant


People also ask

What does execl () do in C?

execl() System Function: In execl() system function takes the path of the executable binary file (i.e. /bin/ls) as the first and second argument. Then, the arguments (i.e. -lh, /home) that you want to pass to the executable followed by NULL. Then execl() system function runs the command and prints the output.

What is the last argument to execl?

The last argument must be (char*)0 , or you have undefined behavior. The first argument is the path of the executable. The following arguments appear in argv of the executed program. The list of these arguments is terminated by a (char*)0 ; that's how the called function knows that the last argument has been reached.

Is execl a system call?

The exec system call is used to execute a file which is residing in an active process. When exec is called the previous executable file is replaced and new file is executed.

How does execv work in C?

The execv function executes the file named by filename as a new process image. The argv argument is an array of null-terminated strings that is used to provide a value for the argv argument to the main function of the program to be executed. The last element of this array must be a null pointer.


1 Answers

execl("/home/vlc",    "/home/vlc", "/home/my movies/the movie i want to see.mkv",    (char*) NULL); 

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

like image 73
AProgrammer Avatar answered Sep 19 '22 14:09

AProgrammer