c - 理解涉及进程的 C 代码

标签 c

有人可以解释为什么第一个代码变量“v”不会改变最后一个 prinft() 中的值,而第二个代码变量“v”会改变。

第一个代码:

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

int v = 5;

int main(){

    pid_t piid;

    piid = fork();

    if(piid==0){
        v += 15;
        return 0;
    }
    else if(piid >0){
        wait(NULL);
        printf("Final value = %d\n",v);
        return 0;
    }
}

我知道这段代码可能涉及 fork() 来创建另一个进程

第二个代码:

#define _GNU_SOURCE
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sched.h>
#include <stdio.h>

// 64kB stack
#define FIBER_STACK 1024*64

int v = 5;

int threadFunction( void* argument )
{
    v += 10;
    return 0;
}

int main(){
    void* stack;
    pid_t pid;


    stack = malloc( FIBER_STACK );
    if ( stack == 0 )
    {
        perror("malloc: could not allocate stack\n");
        exit(1);
    }



    pid = clone( &threadFunction, (char*) stack + FIBER_STACK,
    SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM, 0 );
    if ( pid == -1 )
    {
        perror( "clone" );
        exit(2);
    }


    pid = waitpid( pid, 0, 0 );
    if ( pid == -1 )
    {
        perror( "waitpid" );
        exit(3);
    }


    free( stack );
    printf("Final value = %d\n", v);

    return 0;
}

这段代码是一个线程,但是我无法理解所谓的clone()以及里面的内容。

最佳答案

fork 新进程会创建原始进程的独立且不同的副本。更改流程副本中的某些内容不会更改原始流程中的任何内容。

线程是不同的,它们共享一切。所有线程仍然是同一进程的一部分。

clone系统调用可以创建一个新进程(这就是在 Linux 中实际调用 fork 时发生的情况),它也可以用于创建一个线程,这就是第二个程序中发生的情况。

关于c - 理解涉及进程的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601791/

相关文章:

c - 与外部 SPI 闪存通信时是否应该禁用中断?

c - float 混淆 - 我很困惑 float 说明符是如何出现的

c - 小端宏

c - 这个十六进制算术是如何工作的?

c++ - 在 Linux 中更改线程优先级和调度程序

c - 如何在 C 中的字符串文字中存储私钥?

c - 您如何包含可能存在或可能不存在的头文件?

c - 当我们在 C 中编写 printf() 时,我们是声明它还是定义它?

python - 分配一 block 内存并立即在 C 中释放它失败

c - 粉碎堆栈 - 找不到返回地址