实验一:进程控制实验

实验要求

编写一个多进程并发执行程序。父进程首先创建一个执行 ls 命令的子进程,然后再创建一个执行 ps 命令的子进程,并控制ps 命令总在 ls 命令之前执行。

实验代码

/*
 *exp1.c
 */
#include"exp1.h"
int main(int argc,char *argv[]){
  int i;
  int pid1;
  int pid2;
  int status1;
  int status2;
  char *command1[]={"/bin/ls","-al",NULL};
  char *command2[]={"/bin/ps","-l",NULL};
  signal(SIGINT,(sighandler_t)sigcat);
  pid1=fork();
  if(pid1<0){
    printf("Create Process Fail!\n");
    exit(EXIT_FAILURE);
  }else if(pid1==0){
    printf("Create ls process:\n  pid=%d\n  ppid=%d\n",getpid(),getppid());
    pause();
    status1=execve(command1[0],command1,NULL);
  }else{
    pid2=fork();
    if(pid2<0){
      printf("Create Process Fail!\n");
      exit(EXIT_FAILURE);
    }else if(pid2==0){
      printf("Create ps process:\n  pid=%d\n  ppid=%d\n",getpid(),getppid());
      status2=execve(command2[0],command2,NULL);
    }else{
      waitpid(pid2,&status2,0);
      if(kill(pid1,SIGINT)>=0)
	      printf("%d wake up %d\n",getpid(),pid1);
      waitpid(pid1,&status1,0);
    }
  }
  return EXIT_SUCCESS;
}


/*
 *exp1.h
 */
#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());
}

#makefile

cc=gcc
srcs=exp1.c
head=exp1.h
objs=exp1.o
exp1: $(objs)
	$(cc) $(objs) -o $@
exp1.o: $(head)
	$(cc) -c $(srcs)
clean:
	rm exp1 *.o


实验结果

如图所示



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值