我试图了解fork()/ Linux Kernel如何处理全局变量.
给定代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
输出是2123
在fork()和信号处理程序被调用之后Unix/Linux内核如何处理全局变量?他们是否在孩子和父母之间分享?
我对这段代码的另一个问题是kill()和wait()将如何处理全局变量以及它们将使用什么样的集合 - 父母或孩子?他们会叫信号处理程序???
谢谢 !