谁能解释这个输出(操作系统)?

发布于 2024-10-03 08:24:13 字数 734 浏览 1 评论 0原文

当我学习操作系统课程时,我不明白为什么下面的代码的输出像这样

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h> 

int main (int argc, const char * argv[]) {

    int value = 5;


    pid_t pid = fork();
    printf("pid = %d \n",pid);
    if (pid == 0){
        value+=15;      
        printf("Value ch :%d \n",value);
    }
    else {
        if (pid > 0) {
            wait(NULL);
            printf("Value pr :%d \n",value);
            exit(1);
        }

    }

    return 0;
}

输出:

run
[Switching to process 24752]
Running…
pid = 24756 
pid = 0 
Value ch :20 
Value pr :5 

如果 child 中的值变成 20 为什么从 child value = 到 5 返回后

while i'm studying the operating system course i didnt understand why the output of the code below like this

the code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h> 

int main (int argc, const char * argv[]) {

    int value = 5;


    pid_t pid = fork();
    printf("pid = %d \n",pid);
    if (pid == 0){
        value+=15;      
        printf("Value ch :%d \n",value);
    }
    else {
        if (pid > 0) {
            wait(NULL);
            printf("Value pr :%d \n",value);
            exit(1);
        }

    }

    return 0;
}

OUTPUT:

run
[Switching to process 24752]
Running…
pid = 24756 
pid = 0 
Value ch :20 
Value pr :5 

if value in child became 20 why after returning from child value = to 5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉梦枕江山 2024-10-10 08:24:13

因为 fork() 创建了一个新进程,具有自己的地址空间。该地址空间填充有原始地址空间内容的副本。因此,一个流程中所做的更改不会影响另一流程。

换句话说,这是因为进程不共享内存(除非您使用 mmap() 等显式强制它们共享内存)。

Because fork() creates a new process, with its own address space. This address space is filled with a copy of the contents of the original address space. Therefore, changes made in one process don't affect the other.

In other words, it's because processes don't share memory (unless you explicitly force them to with mmap() and so on).

再浓的妆也掩不了殇 2024-10-10 08:24:13

因为父进程内存被复制到子进程中,子进程内存的进一步更改不会影响父进程的内存。 fork 陷阱很有趣。

Because the parent process memory is copied to the child process and further changes in the child process memory don't affect the parent's. fork pitfalls are interesting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文