#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> //execve()
#include <sys/types.h> //pid_t
#include <sys/wait.h> //waitpid()
int main()
{
int i, j, l, status;
pid_t p;
char *command;
char **argv;
command = (char *)malloc(sizeof(char)*30);
argv = (char **)malloc(sizeof(char *)*30);
while(1)
{
printf("myshell>"); // 输出命令提示符
memset(command, 0, sizeof(char)*30);
if(fgets(command, 30, stdin) == NULL) // 读命令
continue;
l = strlen(command) - 1;
if(command[l] == '\n')
command[l] = 0;
//将读取的一行字符解析到argv中
j = 0;
argv[j] = command;
j++;
l = strlen(command);
for(i=0; i<l; i++)
{
if(command[i] == ' ')
{
command[i] = 0;
if(command[i+1] != ' ')
{
argv[j] = &command[i+1];
j++;
}
}
}
argv[j] = NULL;
//创建进程执行命令
p = fork();
if(p != 0) // 父进程
{
waitpid(-1, &status, 0);
}
else // 子进程
{
execve(argv[0], argv, NULL);
}
}
free(argv);
free(command);
return 0;
}
waitpid()函数解释
参数一:
小于-1表示等待进程组识别码为其绝对值的任何子进程。
等于-1表示等待任何子进程,相当于 wait()。
等于0表示等待进程组识别码与目前进程相同的任何子进程。
大于0表示等待任何子进程识别码为pid的子进程。
参数二:
子进程的结束状态值,如果不在意结束状态值,则
参数 status 可以设成 NULL。
参数三:
参数options提供了一些额外的选项来控制waitpid,如果我们不想使用它们,也可以把options设为0。