博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
父、子进程中的全局变量
阅读量:4588 次
发布时间:2019-06-09

本文共 1709 字,大约阅读时间需要 5 分钟。

子进程创建以后,会继承父进程的全局变量,但是继承的是父进程刚开始全局变量的值。

但是子进程创建以后,子进程修改了变量,或者父进程修改了全局变量的值,父子进程就互相都不影响了。

 

/* 用信号模拟司机售票员问题:创建子进程代表售票员,父进程代表司机 ,同步过程如下: 1 售票员捕捉SIGINT(代表开车),发SIGUSR1给司机, 司机捕捉到该信号之后打印(“move to next station”)。 2 售票员捕捉SIGQUIT(代表靠站),发SIGUSR2给司机, 司机捕捉到该信号之后打印(“stop the bus”)。 3 司机捕捉SIGTSTP(代表车到总站),发SIGUSR1给售票员, 售票员捕捉到该信号之后打印(“all get off the bus”)。  */    #include 
#include
#include
#include
#include
#include
#include
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; }

 

转载于:https://www.cnblogs.com/lialong1st/p/7756667.html

你可能感兴趣的文章
c# 计算目录的大小
查看>>
c# 常见文件操作
查看>>
c# Path类
查看>>
h3c 802.11协议的发展进程
查看>>
ISM无需授权使用的无线频率
查看>>
H3C 802.11b/g工作频段划分图
查看>>
H3C 802.11n
查看>>
H3C 802.11n的频宽模式
查看>>
H3C 40MHz频宽模式
查看>>
H3C Short GI
查看>>
H3C 帧聚合
查看>>
H3C WLAN相关组织和标准
查看>>
H3C 802.11网络的基本元素
查看>>
H3C IEEE 802.11无线局域网工作组
查看>>
H3C 802.11 MAC层工作原理
查看>>
H3C 802.11 WEP加密原理
查看>>
H3C 无线交换机和FIT AP的典型连接
查看>>
H3C FAT AP
查看>>
H3C STA>PC的数据转发
查看>>
H3C 无线交换机的数据转发原理
查看>>