gpt4 book ai didi

c++ - fork 、信号以及它们如何与 C 中的全局变量交互

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:20:22 24 4
gpt4 key购买 nike

我正在尝试了解 fork()/Linux 内核如何处理全局变量。

给定代码:

#include<signal.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#include <sys/types.h>

pid_t pid;
int counter = 2;
void handler1(int sig)
{
counter = counter - 1;
printf("%d", counter);
exit(0);
}
int main()
{
signal(SIGUSR1, handler1); //Install Handler
printf("%d", counter); //Print Parent global variable
pid = fork( ); //Fork(), child pid = 0, parent's pid = positive int.
if (pid == 0) //Parent skips this, child goes into infinite loop
{
while(1) {}; // simulate doing some work
}
kill(pid, SIGUSR1); //While child is the loop, parents calls to terminate the child.
//Child will stop the infinite loop, and will not proceed any
//Will it call handler1 ???

wait(NULL); //Wait for child to be ripped
//Will it call handler1 second time ???
counter = counter + 1; //This will surely increment global variable
printf("%d", counter);
exit(0);
}

输出是2123在调用 fork() 和信号处理程序之后,Unix/Linux 内核如何处理全局变量???他们在 child 和 parent 之间共享吗?

我对这段代码的另一个问题是 kill() 和 wait() 将如何处理全局变量以及它们将使用什么集合—— parent 的还是 child 的??他们会调用信号处理程序吗???

谢谢!

最佳答案

child 获得全局变量的独立拷贝。这两个拷贝不共享

关于c++ - fork 、信号以及它们如何与 C 中的全局变量交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4463315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com