实验三
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
void waiting(), stop();
int wait_mark=1; /*设一个整型变量,作为等待标记*/
int main()
{
int p1,p2;
int stdout1;
while((p1=fork())==-1);/* 创建子进程1*/
if(p1>0)
{
while((p2= fork())==-1); /*创建子进程2*/
if(p2>0) /*父进程运行 */
{
signal(SIGINT , stop);/*父进程接收到 c 信号,转 stop*/
waiting();
kill(p1,16); /*向子进程1发软中断信号16*/
wait(0);
kill(p2,17); /*向子进程2发软中断信号17*/
wait(0);
printf(" Parent process is killed!\n ");
exit(0);
}
else /*子进程2运行*/
{
wait_mark=1; /*设置等待标记*/
signal(17, stop); /*接收到软中断信号17,转 stop */
// waiting();
sleep(4);
lockf(stdout1,1,0);
/* lockf 是锁定屏幕输出,不让其他进程输出到屏幕*/
printf(" Child process2 is killed by parent!\n ");
lockf(stdout1,0,0);/*解锁屏幕输出*/
exit(0);
}
}
else /*子进程1运行 */
{
wait_mark =1;
signal(16, stop); /*接收到软中断信号16,转 stop */
//waiting();
sleep(4);
lockf(stdout1,1,0);
printf(" child process1 ts killed by parent!\n");
lockf(stdout1,0,0);
exit(0);
}
}
void waiting()/*进程没有接收到信号时循环等待,接收到信号后跳出*/
{
while(wait_mark!=0)
{
sleep(1);
}/*当 wait_nark!=0时循环等待,否则跳出循环*/
}
void stop()
{
wait_mark=0;
}