2011-08-09 28 views
0

为了学习的目的,我在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; 
} 

帮助将不胜感激,我真的被困在这里!

+0

是什么execlp不能正确吗? –

+0

在SO上询问并且不检查'execlp'函数的返回码是否真的更容易? :) – 2011-08-09 21:22:37

回答

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 *预计。


我个人更喜欢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); 
+0

Woaaah,谢谢!相比之下,execvp非常容易使用! ..也许我会忘记使用execlp() –

+0

你离开argv [0] out execlp;它应该是'execlp(pointer_array [0],pointer_array [0],pointer_array [1],NULL)' – Dave