操作系统实验1——进程控制实验

实验内容:
编写⼀个多进程并发执⾏程序。⽗进程建⽴两个⼦进程,⾸先创建的让其执⾏ ls 命令,之后创建执⾏让其执⾏ ps 命令,并控制 ps 命令总在 ls 命令之前执⾏。要求⽗进程等待两个⼦进程结束。

#include <sys/types.h>
#include <wait.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h> // 进程⾃定义的键盘中断信号处理函数
typedef void (*sighandler_t) (int);
void sigcat() {
 printf("%d Process continue\n", getpid());
}
int main(int argc,char *argv[])
{
	int i;
	int pid,pid2; int status;
	char *args[] = {"/bin/ls", "-a", NULL};
	char *args2[] = {"/bin/ps", "-a", NULL};
	signal(SIGINT,(sighandler_t)sigcat); pid=fork();
	if(pid<0)
	{
		printf("create process faild!\n"); exit(EXIT_FAILURE);
	}
	if(pid==0)
	{
		printf("I am Child1 process %d, my Father is %d\n", getpid(), getppid()); pause();
		printf("Child1 %d is Running: \n", getpid());
		printf("%s ", args[0]); printf("\n"); status=execve(args[0],args,NULL);
		return 0;
	}
	pid2=fork();
	if(pid2<0)
	{
		printf("create process faild!\n"); exit(EXIT_FAILURE);
	}
	if(pid2==0)
	{
		printf("I am Child2 process %d, my Father is %d\n", getpid(), getppid());
		printf("%s ", args2[0]); printf("\n"); status=execve(args2[0],args2,NULL);
		//return 0;
	}
	printf("I am Parent process %d\n", getpid());
	printf("Parent %d is Waiting for Child2 done\n\n", getpid());
	waitpid(pid2, &status, 0);
	//先等待子进程二退出之后,再唤醒子进程一
	printf("\nParent %d Wakeup Child1 %d\n", getpid(), pid);
	kill(pid,SIGINT);
	printf("Parent %d is Waiting for Child1 done\n\n", getpid());
	waitpid(pid, &status, 0);
	printf("\nMy Child Exit with status = %d\n\n", status);
	return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值