进程管理之二(wait、exec、system的使用)

第一关

#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;
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值