父、子进程中的全局变量
子进程创建以后,会继承父进程的全局变量,但是继承的是父进程刚开始全局变量的值。
但是子进程创建以后,子进程修改了变量,或者父进程修改了全局变量的值,父子进程就互相都不影响了。
/*
用信号模拟司机售票员问题:创建子进程代表售票员,父进程代表司机 ,同步过程如下:
1 售票员捕捉SIGINT(代表开车),发SIGUSR1给司机,
司机捕捉到该信号之后打印(“move to next station”)。
2 售票员捕捉SIGQUIT(代表靠站),发SIGUSR2给司机,
司机捕捉到该信号之后打印(“stop the bus”)。
3 司机捕捉SIGTSTP(代表车到总站),发SIGUSR1给售票员,
售票员捕捉到该信号之后打印(“all get off the bus”)。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static pid_t pid_child, pid_parent;
void child_handler(int sig)
{
if (sig == SIGINT)
{
// kill(pid_parent, SIGUSR1); //错误,此时pid_parent = 0
kill(getppid(), SIGUSR1); //正确
}
if (sig == SIGQUIT)
{
// kill(pid_parent, SIGUSR2); //错误,此时pid_parent = 0
kill(getppid(), SIGUSR2); //正确
}
if (sig == SIGUSR1)
printf("all get off the bus\n");
}
void parent_handler(int sig)
{
if (sig == SIGUSR1)
printf("move to next staion\n");
if (sig == SIGUSR2)
printf("stop the bus\n");
if (sig == SIGTSTP)
kill(pid_child, SIGUSR1);
}
int main(void)
{
pid_t ret;
ret = fork();
if (ret < 0)
{
printf("fork fail");
exit(1);
}
else if (ret == 0)
{
/* child process */
signal(SIGTSTP, SIG_IGN);
signal(SIGINT, child_handler);
signal(SIGQUIT, child_handler);
signal(SIGUSR1, child_handler);
while (1)
{
pause();
}
}
else
{
/* parent process */
pid_child = getpid();
// pid_parent = getpid();
printf("pid_child = %d\n", pid_child);
printf("pid_parent = %d\n", pid_parent);
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGUSR1, parent_handler);
signal(SIGUSR2, parent_handler);
signal(SIGTSTP, parent_handler);
while (1)
{
pause();
}
}
return 0;
}

浙公网安备 33010602011771号