实验要求
编写一个多进程并发执行程序。父进程首先创建一个执行 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
如图所示