动态参数传递给execlp()函数用C [英] dynamic parameter passing to execlp() function in C

查看:300
本文介绍了动态参数传递给execlp()函数用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了让事情简单,我已经修改了我的计划。我想要做的就是接受运行期间任意数量的参数,并把它传递给 execlp()。我使用固定长度的二维数组 M [] [] ,使得任何未使用(剩余)插槽可能为 NULL 传递到 execlp (在这种情况下, M [2] [] )。

To make things simple, I have modified my program. What I want to do is accept any number of parameters during runtime and pass it to execlp(). I am using fixed length 2d array m[][] such that any unused (remaining) slots maybe passed as NULL to execlp (in this case m[2][]).

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

int main() {
    char m[3][5], name[25];
    int i;
    strcpy(name, "ls");
    strcpy(m[0], "-t");
    strcpy(m[1], "-l");
    //To make a string appear as NULL (not just as an empty string)
    for(i = 0; i < 5; i++)
        m[2][i] = '\0'; // or m[2][i] = 0 (I've tried both)
    execlp(name, m[0], m[1], m[2], '\0', 0, NULL);  
    // Does not execute because m[2] is not recognized as NULL
    return 0;
    }

我该怎么办呢?

推荐答案

由于要接受任意数量的参数,你的目标应该是使用的 execvp() 而不是 execlp()

Since you want to accept any number of arguments, what you should aim to use is execvp() instead of execlp():

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int main(void)
{
    char *argv[] = { "ls", "-l", "-t", 0 };
    execvp(argv[0], argv);
    fprintf(stderr, "Failed to execvp() '%s' (%d: %s)\n", argv[0], errno,
            strerror(errno));
    return(EXIT_FAILURE);
}

execvp()函数调用参数任意长度列表中数组的形式,不像 execlp()在这里,你写的任何单呼只需参数固定长度列表。如果你想容纳2,3,4,...参数,你应该写为每个不同数量的参数单独调用。还有什么是不完全可靠的。

The execvp() function takes an arbitrary length list of arguments in the form of the array, unlike execlp() where any single call that you write takes only a fixed length list of arguments. If you want to accommodate 2, 3, 4, ... arguments, you should write separate calls for each different number of arguments. Anything else is not wholly reliable.

这篇关于动态参数传递给execlp()函数用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆