I am reading GNU/Linux application programming the 2nd edition,you can reach what am reading from here.After I write the code similar to his,but it work strangely:
$ ./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
The first and second cases are ok,but the third and forth ones somewhat need two quit to quit.This is not what i am expecting.I guess something is wrong with fork(),or the waitpid(),but this still got unsolved after asking a few people around me.Now is summer time, i.e. summer holiday,I got no more mates to go for.Thanks always.
#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;
}
Normally, if
execlpsucceeds, your child process becomes the new process, and thus execution of your code effectively stops at that point.Now the
execlpfailed, you print out the error, and continue the child process as if nothing happened! You shouldexit(0)the child, if theexeclpfailed.