سؤال

وأنا أكتب مصغرة قذيفة للحصول على أكثر دراية إدارة عملية يونكس في C. انها قراءة الاشياء من سطر الأوامر ويمر عبر هذه الحجج execlp إلى النظام.

# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>

#define MAXSIZE 100

char prompt[MAXSIZE];

int main(void)
{
   pid_t pid;

   printf("> ");

   // read stuff 
   if (fgets(prompt, MAXSIZE, stdin) == NULL){
      printf("Input validation error!");
      abort();
   }
   // printf("DEBUG: %s" , prompt);

   if (strcmp(prompt, "exit")==0) abort();


   if ((pid=fork())<0){       // copy process

      printf("Process error!");
      abort();
   }

   if (pid==0){                // exec in son-prcess

      char *command=(char*)strtok(prompt, " ");
      execlp(command, command, 0);  // overwrite memory

      printf("Error, command not found!");
      abort();
   } else {

      waitpid(pid, 0, 0);
    }
}

في الحقيقة هذا من شأنه أن يكون ذلك، ولكن أنا لا أحصل على أي الإخراج من execlp(). لا أحد يعرف لماذا هذا؟

هل كانت مفيدة؟

المحلول

وحاولت تشغيل البرنامج، وذلك بسبب فشل command تحتوي على \n (السطر). I تغييره عن طريق وضع \n بدلا من "" في strtok وثم ركض بنجاح.

في التفاصيل:

  if (pid==0){                // exec in son-prcess
      char *command=(char*)strtok(prompt, "\n");
      printf ("'%s'\n", command);
      execlp (command, command, 0);  // overwrite memory
      printf("Error %d (%s)\n", errno, strerror (errno));
      abort();
   } else {

واختبار المدى:

$ ./a.out 
> ls
'ls'
(usual ls behaviour)

نصائح أخرى

وKinopiko وجدت بالفعل لماذا لا يعمل، ولكن السبب كنت لا ترى أي رسالة الخطأ هو أن لديك قذيفة موجه والكتابة فوقه. محاولة وضع سطر جديد في النهاية:

printf("Error, command not found!\n");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top