Execl () on Ubuntu

I am learning linux programming and came across an exec function that is very useful. But the problem with the arguments to the exec function is very confusing, and I cannot figure out which argument is for what purpose. The following execl() code calls a function from a child object created with fork() . What is the purpose of the last argument ( NULL ) in execl() ?

 execl("/bin/ls","ls","-l",NULL); 

If anyone can explain what the purpose of the NULL argument and other arguments is and the purpose of the arguments to the exec() family function, that would be a big help for me!

+4
source share
3 answers

To create undefined behavior. This is not a legal execl call. The correct call could be:

 execl( "/bin/ls", "ls", "-l", (char*)0 ); 

The final argument must be (char*)0 , or you have undefined behavior. The first argument is the path of the executable file. The following arguments are displayed in the argv executable. The list of these arguments ends with (char*)0 ; that as the called function knows that the last argument has been reached. In the example above, for example, the executable in "/bin/ls" will replace your code; in its main , it will have argc equal to 2, with argv[0] equal to "ls" , and argv[1] equal to "-l" .

Right after this function you should have error handling code. ( execl always returns -1 when it returns, so you do not need to try this. And it returns only in case of some kind of error.)

+9
source

The exec functions are variable: they take a variable number of parameters, so you can pass a variable number of arguments to the command. Functions should use NULL as a marker to mark the end of the argument list.

Inside the variational functions there is a loop that will iterate over a variable number of arguments. These loops need a final condition. In some cases, such as printf , the actual number of arguments may be inferred from another argument. In other functions, NULL used to indicate the end of a list.

Another option would be to add an additional function parameter for the number of arguments, but this would make the code a little more fragile, requiring the programmer to control the additional parameter, and not just always use NULL as the final argument.

You will also see (char *) 0 used as a marker:

 execl("/bin/ls", "ls", "-l", (char *) 0); 
+4
source

In /usr/include/libio.h , since gcc 2.8 (long ago) NULL is defined as null ( reserved for built-in functions), before that NULL was (void *)0 , which is indistinguishable from (char *)0 in the varargs situation , since the type is not passed, the exception is if __cplusplus , in which case NULL is defined as 0.

The safe thing, especially if you have a 64-bit architecture, is to explicitly use (void *)0 , which is defined as compatible with any pointer and not relying on any dodgy #defines that might appear in the standard library.

0
source

Source: https://habr.com/ru/post/1437228/


All Articles