#include "pctl.h"
int main(int argc, char *argv[])
{
int m=2;
int i;
int seconds=3;
int pid1;
int pid2; //存放子进程号
int status1;
int status2; //存放子进程返回状态
char *args1[] = {"/bin/ls","-all",NULL}; //子进程1要缺省执行的命令
char *args2[] = {"/bin/ps","-l",NULL}; //子进程2要缺省执行的命令
signal(SIGINT,(sighandler_t)sigcat); //注册一个本进程处理键盘中断的函数
while(m!=0)
{
pid1=fork() ; //建立子1进程
if(pid1<0) // 建立子进程1失败?
{
printf("Create Process1 fail!\n");
exit(EXIT_FAILURE);
}
if(pid1 == 0) // 子进程1执行代码段
{
//报告父子进程进程号
printf("I am Child process1 %d\nMy father is %d\n",getpid(),getppid());
m=0;
pause(); //暂停,等待键盘中断信号唤醒
//子进程被键盘中断信号唤醒继续执行
printf("%d child will Running: \n",getpid()); //
for(i=0; args1[i] != NULL; i++) printf("%s ",args1[i]);
printf("\n");
//装入并执行新的程序
status1 = execve(args1[0],args1,NULL);
}
else //父进程执行代码段
{
printf("\nI am Parent process %d\n",getpid()); //报告父进程进程号
pid2=fork();//建立子进程2
if(pid2<0) // 建立子进程2失败?
{
printf("Create Process2 fail!\n");
exit(EXIT_FAILURE);
}
if(pid2 == 0) // 子进程2执行代码段
{ //报告父子进程进程号
m=0;
printf("I am Child process2 %d\nMy father is %d\n",getpid(),getppid());
for(i=0; args2[i] != NULL; i++) printf("%s ",args2[i]);
printf("\n");
//子进程2开始执行
status2=execve(args2[0],args2,NULL);
}
else
{
sleep(1);
if(kill(pid1,SIGINT)>=0)
printf("%d wakeup %d child.\n",getpid(),pid1);
printf("But %d don't Wait for %d child done.\n\n",getpid(),pid1);
}
}
unsigned sleep(seconds);
}
}
Pctl.h文件
#include <sys/types.h>Makefile文件
#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());
}
head = pctl.h
srcs = pctl.c
objs = pctl.o
opts = -g -c
all: pctl
pctl: $(objs)
gcc $(objs) -o pctl
pctl.o: $(srcs) $(head)
gcc $(opts) $(srcs)
clean: