繁体   English   中英

C 编程 - execlp() 帮助?

[英]C Programming - execlp() help?

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

一切正常,除了 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;
}

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

这是不对的:

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

execlp 被声明为int execlp(const char *file, const char *arg, ...); . 警告应该清楚地表明您不能在需要char *的地方传递char **


就我个人而言,我非常喜欢execvp 它还允许您将许多 arguments 传递给新进程。

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

你也可以试试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM