After forking, are global variables shared?
Consider this simple code:
int myvar = 0;
int main() {
if (fork()>0) {
myvar++;
} else {
// father do nothing
}
}
When child increments myvar, is the value shared with the father (like pthread)?
No and yes.
No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents.
But yes, the OS actually does share the pages initially, because fork implements copy-on-write which means that provided none of the processes modifies the pages, they are shared. This is, however, an optimisation which can be ignored.
If you wanted to have shared variables, put them in an anonymous shared mapping (see mmap()) in which case they really will get shared, with all the caveats which come with that.
fork()
ing은 포킹 시 부모 프로세스의 정확한 복사본을 만듭니다.단, 그 후fork()
완료, 자녀는 완전히 다른 존재이며 부모에게 보고하지 않습니다.
In other words, no, the parent's global variables will not be altered by changes in the child.
After fork(), the entire process, including all global variables, is duplicated. The child is an exact replica of the parent, except that it has a different PID(Process Id), a different parent, and fork() returned 0. Global variables are still global within its own process. So the answer is no, global variables are not shared between processes after a call to fork().
No, since global variables are not shared between processes unless some IPC mechanism is implemented. The memory space will be copied. As a consequence, the global variable in both processes will have the same value inmediately after fork, but if one changes it, the other wont see it changed.
Threads on the other hand do share global variables.
ReferenceURL : https://stackoverflow.com/questions/4298678/after-forking-are-global-variables-shared
'programing' 카테고리의 다른 글
bootstrap-vue navbar 항목 드롭다운을 사용하여 텍스트 색상 변경 (0) | 2022.07.31 |
---|---|
Nuxt / Vue ... mapMutations를 올바르게 사용하는 방법 (0) | 2022.07.31 |
vuejs2: vuex 스토어를 vue-router 컴포넌트에 전달하는 방법 (0) | 2022.07.31 |
테스트 없이 Maven 패키지/설치(스킵 테스트) (0) | 2022.07.31 |
Chart.js의 툴팁을 커스터마이즈합니다. (0) | 2022.07.31 |