Command Line Arguments not getting executed in C

六眼飞鱼酱① 提交于 2020-01-06 06:33:06

问题


I am trying to pass arguments to execl() function for ls command. But when I pass

/bin/ls -l -a

as arguments to my program, the execl() function doesn't recognise the last two arguments. Why is that?Here is the code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
int i,childpid;

if(argc!=4)
{
    printf("you didn't provide any commandline arguments!\n");
    return 0;
}

childpid=fork();

if(childpid<0)
{
    printf("fork() failed\n");
    return 0;
}
else
    if(childpid==0)
    {
         printf("My ID %d\n\n",getpid());
        execl(argv[1],argv[2], argv[3],NULL);

        printf("If you can see this message be ware that Exec() failed!\n");
    }

    while(wait(NULL)>0);

    printf("My ID %d, Parent ID %d, CHild ID %d\n", getpid(),getppid(),childpid);

    return 0;
}

I am on Ubuntu.

Regards


回答1:


When running your program /bin/ls appears to ignore the -l argument because it is passed in the position reserved for argv[0], which is normally the (rather useless) program name.

Specifically, the first argument to execl is the program to run, and the remaining arguments get copied to argv vector as-is. Since argv[0] is expected to contain the program name and the actual arguments begin from argv[1], you must compensate by providing the program name twice:

execl(argv[1], argv[1], argv[2], argv[3], (char *) NULL);



回答2:


One mistake in the code is the use of NULL as the last argument to execl(). From man execl:

The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

See the question How do I get a null pointer in my programs? from the C FAQ, which specifically mentions excel() in its example.




回答3:


The code does not work for me until I add #include<unistd.h>

As far as i know the functions exec,execl etc are declared in unistd.h and not in stdlib.h.

I do get warnings if i compile only with stdlib.h and stdio.h.

test.c: In function ‘main’: test.c:24:9: warning: incompatible implicit declaration of built-in function ‘execl’ [enabled by default]

There if you add unistd.h, and change the exec call to

execl(argv[1], argv[1], argv[2], argv[3],NULL);

your program should work.



来源:https://stackoverflow.com/questions/13438643/command-line-arguments-not-getting-executed-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!