1
我正在爲一個操作系統類構建一個shell,它必須使用exec()或其一個變體來執行外部命令。目前,我正在使用execlp(command,command_parameters, (char *) NULL)
。這運行命令就好了(例如ls
返回一個標準的目錄列表),但似乎沒有解析任何參數(例如運行mkdir hello
會引發錯誤「hello:missing operand ...嘗試'hello --help'for 。更多信息)我在想什麼C execlp()沒有正確解析參數字符串
else // Try to handle an external command
{
char *command_parameters = malloc(sizeof(raw_command)-sizeof(command));
strcpy(command_parameters, raw_command+strlen(command)+1);
pmesg(1, "Command is %s.\n", command);
pmesg(1, "The command parameters are %s.\n", command_parameters);
pid_t pid = fork();
pmesg(1, "Process forked. ID = %i. \n", pid);
int status;
if (fork < 0)
{
printf("Could not fork a process to complete the external command.\n");
exit(EXIT_FAILURE);
}
if (pid == 0) // This is the child process
{
pmesg(1, "This is the child process, running execlp.\n");
if (execlp(command, command_parameters, (char *) NULL) < 0)
{
printf("Could not execute the external command.\n");
exit(EXIT_FAILURE);
}
else { pmesg(1, "Executed the child process.\n"); }
}
else {while(wait(&status) != pid); } // Wait for the child to finish executing
pmesg(1, "The child has finished executing.\n");
}
(pmesg
是一個調試標籤,打印)給予一定的調試級別的聲明
感謝
什麼是鑄造字符指針爲NULL的含義是什麼? – 2016-10-14 08:12:05