进程习题1

  1. 编写一个程序,使其产生一个子进程c,并使用exec函数簇中的任意版本,使得子进程执行系统命令ls -l查看某个文件的详细信息,
    父进程判断子进程是否执行成功?
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
	pid_t son=fork();

	if(son>0) //父进程
	{
		int status;
		wait(&status);
		if(WIFEXITED(status))  //判断子进程是否正常退出
		{
			printf("正常退出,返回值为:%d\n",WIFEXITED(status));
		}
	}
	if(son == 0) //子进程
	{
		int ret=execl("/bin/ls","ls","-l","day1.c",NULL);
		if(ret == -1)
		{
			perror("execl error\n");
		}
		exit(0);
	}

	return 0;
}
  1. 写一个程序,创建嵌套的三个子进程,获取不同的子进程的父进程pid
    尝试退出函数和等待函数waitpid监听
/*
写一个程序,创建嵌套的三个子进程,获取不同的子进程的父进程pid
   尝试退出函数和等待函数waitpid监听
*/
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
	pid_t son1,son2,son3;//子进程
	int status1,status2,status3;//状态值
	int ret1,ret2,ret3;
	
	//创建进程1
	son1=fork();
	if(son1 == 0)//子进程
	{
		printf("父进程的pid=%d\n",getppid());
		exit(10);//退出子进程
	}
	else if(son1 > 0)//父进程
	{
		//创建进程2
		son2=fork();
		if(son2 == 0)//子进程
		{
			printf("父进程的pid=%d\n",getppid());
			exit(15);//退出子进程
		}
		else if(son2 > 0)//父进程
		{
			//创建进程3
			son2=fork();
			if(son2 == 0)//子进程
			{
				printf("父进程的pid=%d\n",getppid());
				exit(20);//退出子进程
			}
			else if(son2 > 0)//父进程
			{
				printf("我是父进程3\n");
                ret3=waitpid(-1,&status3,0);				
			} 
			printf("我是父进程2\n");
            ret2=waitpid(-1,&status2,0);	
		}
		printf("我是父进程3\n");
        ret1=waitpid(-1,&status1,0);	
	}
	printf("等待状态值1%d  状态值2%d 状态值3%d\n",ret1,ret2,ret3);
	printf("等待退出值1%d  退出值2%d 退出值3%d\n",
			               WEXITSTATUS(status1),WEXITSTATUS(status2),WEXITSTATUS(status3));
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值