簡體   English   中英

execvp()在我自己的shell中不執行任何命令

[英]execvp() not executing any command in my own shell

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LINE 80 /* Maximum  length of command*/
struct node
{
 char commandName[41];
 struct node *next;
}*start=NULL;


void insert_at_beg(char cmd[])
{
 struct node *new_node,*current;

 new_node=(struct node *)malloc(sizeof(struct node));

 if(new_node == NULL)
 printf("nFailed to Allocate Memory");

 strcpy(new_node->commandName, cmd);
 new_node->next=NULL;

 if(start==NULL)
 {
  start=new_node;
  current=new_node;
 }
 else
 {
  new_node->next=start;
  start=new_node;
 }
}
void display()
{
 struct node *temp;
 temp=start;
 while(temp!=NULL)
 {
  printf("\t%s\n",temp->commandName);
  temp=temp->next;
 }
}

上面的代碼是一個鏈表,它是使用結構實現的,以在我自己的shell中實現歷史記錄功能。 insert_at_beg()用於將在節點上作為節點輸入的命令添加到列表中,而display()用於顯示列表。

下面是主要功能。 在此功能中,我創建了自己的外殼

int main()
{
 char *args[MAX_LINE/2+1]; /* Command Line Argument*/
 int should_run=1, status, i, num, error;
 pid_t pid;
 char str[41];
 char teststr[10]={"history\0"};
 char temprory[41];
 const char delimiter[2]=" ";
 char *token;

 while(should_run)
 {
i=0;
printf("osh>");
fflush(stdout);

fgets(str, sizeof str, stdin);
str[strlen(str)-1]='\0';
strncpy(temprory, str, sizeof(temprory));

token=strtok(str, " ");

    while(token)
    {
       args[i]=strdup(token);

       i++;
       token=strtok(NULL, " ");
    }

    insert_at_beg(args[0]);

    if((strcmp(args[0],teststr))==0)
    {
        display();
    }
    else
    {
        ;
    }

    pid=fork();
    if(pid<0)   // error in creating child process
    {
       printf("\tError in creating child process\n");
    }       
    else if(pid==0)    //child process will execute this block
    {

       error=execvp(args[0], args);   //execvp() always return -1 for any  
        if(error==-1)             //command I type in i.e. that command
        {                         //is not found and hence not executed.
            printf("bash:command not found\n");
        }
                 exit(1);
    }
    else        //parent process will execute this block
    {
       pid=wait(&status);

    if(!strcmp(args[0], "exit"))
    {
            should_run=0;
    }
    }
    }
   return 0;
 }

如何解決這個問題並使它起作用? 長期以來,我一直處於這種情況。 在這里需要幫助。

引自man 3 execvp

execv(),execvp()和execvpe()函數提供了一個指向以空字符結尾的字符串的指針的數組,這些字符串表示新程序可用的參數列表。 按照慣例,第一個參數應指向與正在執行的文件關聯的文件名。 指針數組必須以空指針終止。

雖然您沒有使用空指針終止args數組。

添加此行:

args[i] = NULL;

在循環執行之后:

while(token)
{
   args[i]=strdup(token);
   i++;
   token=strtok(NULL, " ");
}

解決您的問題。 (至少在我的筆記本電腦上,問題已解決。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM