[英]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.