C编程 - execlp()有帮助吗?

时间:2011-08-09 21:16:45

标签: c unix shell exec

我在C中创建一个用于学习目的的shell,到目前为止,我已经到了可以通过fgets()输入字符串的点,字符串被分解为“块”,然后这些块传递给execlp()。第一个块是命令的名称,后续的块是命令参数。

除了execlp()调用之外,一切正常。但根据手册页,我看不出我做错了什么,这对我来说都是合法的!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

#define MAX_CHUNKS 10

/*==========================================================================
 *  Given a string, Break it down into chunks. Separated by ' ', skipping \n
 * ========================================================================*/
int break_down_string(char *input_string, char *pointer_array[MAX_CHUNKS])
{
        char *p = input_string, buffer[100]={0};//Initialize buffer to zero's.
        short int index = 0, space_count = 0, i;


    strncat(p, " ", 1);

    while (*p != '\0')
    {   
        if (index == MAX_CHUNKS) break; //End if MAX_CHUNKS chunks taken from string.
        if (*p == '\n'){ //Skip newline characters.
            p++;
            continue;
            }

        if (*p == ' ') //Space Detected 
        {
            if (space_count == 0)
            {
                pointer_array[index] = (char *)malloc(sizeof(char) * strlen(buffer) +1);
                strncpy(pointer_array[index], buffer, strlen(buffer));
                strncat(pointer_array[index], "\0", 1);
                bzero(buffer, sizeof(buffer));
                index++;
            }
            space_count = 1;
        }
        else //Non-Space Detected
        {
            if (space_count > 0) space_count = 0;
            strncat(buffer, p, 1);
        }
        p++;
    }

pointer_array[index] = NULL; //Set end pointer to NULL for execlp().

return 0;
}



/*--------------------------------MAIN()-----------------------------------*/
int main(void)
{
    char buffer[100];
    char *pointer_array[MAX_CHUNKS]; //Array which will hold string chunks

    fgets(buffer, sizeof(buffer), stdin); 

    break_down_string(buffer, pointer_array);

    if (fork() == 0)
    {
        printf("Child process!\n");
        execlp(pointer_array[0], (pointer_array+1), NULL);
    }
    else
    {
        printf("Parent process!\n");
    }

return 0;
}

非常感谢帮助,我真的被困在这里了!

1 个答案:

答案 0 :(得分:2)

这是不对的:

char *pointer_array[MAX_CHUNKS];
execlp(pointer_array[0], (pointer_array+1), NULL);

execlp声明为int execlp(const char *file, const char *arg, ...);。警告应该非常清楚,您无法通过char **预期char *。{/ p>


我个人更喜欢execvp。它还允许您将许多参数传递给新进程。

/* Make sure the last element of pointer_array is NULL. */
execvp(pointer_array[0], pointer_array);

您也可以尝试:

execlp(pointer_array[0], pointer_array[1], NULL);