dynamic parameter passing to execlp() function in C

巧了我就是萌 提交于 2019-12-10 11:23:53

问题


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

How do i do it?


回答1:


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

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.




回答2:


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

int main() {
    char *args[] = {"ls", "-t", "-l" };
    execlp(args[0], args[0], args[1], args[2], NULL);
    perror( "execlp()" );
    return 0;
    }

For simplicity I replaced all the string management stuff by a fixed pointer array. There is only one final NULL argument needed for execlp(), execle() would also need the environment pointer after the NULL arg.




回答3:


 char m[3][5];

This is a 2D array of characters.

m[2] is a element of the 2D array that is it it a 1D Array of characters.

So it always having a constant address.And it never be NULL as it is a constant address which can not be NULL.Again it can not be assigned to NULL so you have to use NULL as last parameter.

execlp() use NULL as terminating argument so you have bound to mention it.

If you use command line argument then last command line argument is always NULL.SO last element of char *argv[] argument can be used as terminating argument in execlp() function.



来源:https://stackoverflow.com/questions/11818491/dynamic-parameter-passing-to-execlp-function-in-c

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