第一关
#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
{
//父进程
int status;
if(waitpid(-1, &status, 0) != -1)
{
if(WIFEXITED(status))
return WEXITSTATUS(status);
}
exit(0);
}
/********** END **********/
return status;
}
第二关
#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 **********/
}
}
第三关
#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;
}