本文介绍了命令行参数未在C中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将参数传递给ls命令的execl()函数.但是当我通过

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

/bin/ls -l -a

作为我程序的参数,execl()函数无法识别最后两个参数.为什么呢?代码如下:

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;
}

我在Ubuntu上.

致谢

推荐答案

在运行程序时,/bin/ls似乎忽略了-l参数,因为它是在为argv[0]保留的位置传递的,通常是(相当无用的)程序名称.

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.

具体地说,execl的第一个参数是要运行的程序,其余参数按原样复制到argv向量.由于期望argv[0]包含程序名称,并且实际参数以argv[1]开头,因此您必须通过两次提供程序名称来补偿:

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);

这篇关于命令行参数未在C中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:40