题目描述、要求等就不过多赘诉
让我们直接上代码!!!!
第1关:进程等待
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
/************************
* 返回值: 调用成功且子进程正常退出返回退出代码,否则返回-1
*************************/
int waitProcess()
{
int status = -1;
/********** BEGIN **********/
pid_t pid;
pid = fork();
if(pid == -1){
//创建进程失败
return -1;
}
else if(pid == 0){
//子进程
sleep(2);
printf("This is child process\n");
exit(1);
}
else{
//父进程
if(waitpid(-1, &status, 0) != -1){
if(WIFEXITED(status))
return WEXITSTATUS(status);
}
exit(0);
}
/********** END **********/
return status;
}
第2关:进程创建操作-exec函数族
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/************************
* 提示: 在子进程中如果执行exec函数失败要使用exit函数正确退出子进程
*************************/
int execlProcess()
{
pid_t pid = vfork();
if(pid == -1){
printf("创建子进程失败(%s)\n", strerror(errno));
return -1;
}
else if(pid == 0){
//子进程
/********** BEGIN **********/
if(execlp("touch", "touch", "testFile", NULL) < 0){
//执行execlp函数失败
exit(-1);
}
/********** END **********/
}
else{
//父进程
/********** BEGIN **********/
printf("Parent Process");
/********** END **********/
}
}
第3关:进程创建操作-system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
/************************
* 返回值: 调用成功返回命令的状态码,失败返回-1
*************************/
int createProcess()
{
int ret = -1;
/********** BEGIN **********/
ret=system("mkdir testDir");
if(ret == -1){
return -1;
}
/********** END **********/
return ret;
}
第4关:实现一个简单的命令解析器
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
void RShell(char *cmd[], int commandNum)
{
pid_t pid;
//for (int i = 0; i < commandNum; i++) {
int i = 0;
while(commandNum) {
pid = fork();
if (pid == -1) {
printf("创建进程失败(%s)!", strerror(errno));
return -1;
} else if (pid == 0) {
char *file;
char *point = NULL;
char *tmpArg[10];
point = strtok(cmd[i], " ");
file = point;
int index = 0;
while (point != NULL) {
if (index == 9)
break;
tmpArg[index++] = point;
point = strtok(NULL, " ");
}
char **arg = malloc(sizeof(char *) * (index + 1));
int i;
for (i = 0; i < index; i++)
arg[i] = tmpArg[i];
arg[index] = NULL;
if (execvp(file, arg) < 0) {
//执行execvp函数失败
exit(-1);
}
} else {
int status;
wait(&status);
}
commandNum--;
i++;
}
}