爲了學習的目的,我在C中創建了一個shell,到目前爲止,我已經到了可以通過fgets()輸入一個字符串的地步,字符串被分解爲「塊」,然後這些塊傳遞給execlp()。第一個塊是命令的名稱,後面的塊是命令參數。C編程 - 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;
}
幫助將不勝感激,我真的被困在這裏!
是什麼execlp不能正確嗎? –
在SO上詢問並且不檢查'execlp'函數的返回碼是否真的更容易? :) – 2011-08-09 21:22:37