将下面的程序保存到fork.c里面。从运行的结果看,父子进程中的局部变量或者全局变量都没有被彼此影响。
-
?#include<stdio.h>
-
#include<signal.h>
-
#include <stdlib.h>
-
//#include <unistd.h>
-
//变量在不同进程中是相互独立的
-
int wait_mark;
-
int g_temp = 21;
-
void waiting()
-
{
-
while (wait_mark == 1);
-
}
-
-
void stop()
-
{
-
wait_mark = 0;
-
}
-
-
int main()
-
{
-
int p1, p2;
-
int temp = 3;
-
while ((p1 = fork()) == -1);
-
if (p1 == 0) //第一个子进程
-
{
-
wait_mark = 1;
-
printf("Child Process11 temp1 = %d \n",temp);
-
printf("Child Process11 g_temp1 = %d \n",g_temp);
-
signal(SIGINT, SIG_IGN);//忽略来自键盘的中断信号 ( ctrl + c )
-
signal(16, stop);
-
waiting();
-
lockf(1, 1, 0); //加锁
-
printf("Child Process11 is Killed by Parent!\n");
-
printf("Child Process11 temp2 = %d \n",temp);
-
temp = 6;
-
printf("Child Process11 g_temp2 = %d \n",g_temp);
-
g_temp = 23;
-
lockf(1, 0, 0); //解锁
-
exit(0);
-
}
-
else
-
{
-
while ((p2 = fork()) == -1);
-
if (p2 == 0) //第二个子进程
-
{
-
wait_mark = 1;
-
printf("Child Process12 temp1 = %d \n",temp);
-
printf("Child Process12 g_temp1 = %d \n",g_temp);
-
signal(SIGINT, SIG_IGN);//忽略来自键盘的中断信号 ( ctrl + c )
-
signal(17, stop);
-
waiting();
-
lockf(1, 1, 0); //加锁
-
printf("Child Process12 is Killed by Parent!\n");
-
printf("Child Process12 temp2 = %d \n",temp);
-
temp = 5;
-
printf("Child Process12 g_temp2 = %d \n",g_temp);
-
g_temp = 24;
-
lockf(1, 0, 0);//解锁
-
exit(0);
-
}
-
else//父进程
-
{
-
wait_mark = 1;
-
temp = 4;
-
g_temp = 22;
-
printf("Parent temp1 = %d \n",temp);
-
printf("Parent g_temp1 = %d \n",g_temp);
-
signal(SIGINT, stop);//注册来自键盘的中断信号 ( ctrl + c ) ,中断后跳到stop函数中运行
-
waiting();
-
kill(p1, 16);
-
kill(p2, 17);
-
wait(0);
-
wait(0);
-
printf("Parent Process is Killed!\n");
-
printf("Parent temp2 = %d \n",temp);
-
printf("Parent g_temp2 = %d \n",g_temp);
-
exit(0);
-
}
-
}
-
}
在当前目录下
[chenyun fork]$
gcc fork.c -o fork.o
结果打印如下:
[chenyun fork]$
./fork.o
Child Process11 temp1 = 3
Child Process11 g_temp1 = 21
Parent temp1 = 4
Parent g_temp1 = 22
Child Process12 temp1 = 3
Child Process12 g_temp1 = 21
^CChild Process11 is Killed by Parent!
Child Process11 temp2 = 3
Child Process11 g_temp2 = 21
Child Process12 is Killed by Parent!
Child Process12 temp2 = 3
Child Process12 g_temp2 = 21
Parent Process is Killed!
Parent temp2 = 4
Parent g_temp2 = 22
[chenyun fork]$
注:程序运行中间按ctrl+C会中断父进程,父进程会发kill 16消息给子进程1,发kill 17消息给子进程2。
阅读(1051) | 评论(0) | 转发(0) |