strtok的和execlp在微型壳
题
我正在写一个小型外壳,以获得更多熟悉C. Unix进程管理它的命令行从阅读的东西,并通过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
(新行)。我改变它通过把\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已经发现为什么这是行不通的,但你没有看到任何错误消息的原因是,你的shell提示覆盖它。尝试把一个新行结尾:
printf("Error, command not found!\n");
不隶属于 StackOverflow