【发布时间】:2010-08-08 13:33:10
【问题描述】:
我正在阅读GNU/Linux application programming the 2nd edition,你可以从here获得正在阅读的内容。在我写了类似于他的代码后,它的工作原理很奇怪:
$ ./shell
./shell>>quit
$ ./shell
./shell>>date
Sun Aug 8 21:19:37 CST 2010
./shell>>quit
$ ./shell
./shell>>abc
execlp failed: No such file or directory
./shell>>quit
./shell>>quit
$./shell
./shell>>abcd execlp
execlp failed: No such file or directory
./shell>>quit
./shell>>quit
第一种和第二种情况都可以,但是第三种和第四种情况需要两个 quit 才能退出。这不是我所期望的。我猜 fork( ),或者waitpid(),但是问了我身边的几个人后,还是没有解决。现在是暑假时间,即暑假,我没有更多的伙伴可以去。永远感谢。
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LINE_LEN 80
int main(int argc,char* argv[])
{
pid_t pid;
char cmd[LINE_LEN+1]={'\0'};
while(1)
{
printf("%s>>",argv[0]);
if(fgets(cmd,sizeof(cmd),stdin)==NULL)
{
perror("fgets failed");
break;
}
cmd[strlen(cmd)-1]='\0';
if(strncmp(cmd,"quit",4)==0)
{
break;
}
if((pid=fork())==-1)
{
perror("fork failed");
break;
}else if(pid==0)
{
//TODO no option can be specified for cmd
execlp(cmd,cmd,NULL);
perror("execlp failed");
}else
{
waitpid(pid,NULL,0);
}
}
return 0;
}
【问题讨论】: