出于学习目的,我正在用 C 创建一个 shell,到目前为止,我已经达到了可以通过 fgets() 输入字符串的程度,该字符串被分解为“ block ”,然后这些 block 被传递给 execlp()。第一个 block 是命令的名称,后续 block 是命令参数。
除了 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
。它还允许您将许多参数传递给新进程。
/* Make sure the last element of pointer_array is NULL. */
execvp(pointer_array[0], pointer_array);
您还可以尝试:
execlp(pointer_array[0], pointer_array[1], NULL);
关于C 编程 - execlp() 有帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7003113/