C语言 使用指针时会发生争用吗?

muk1a3rh  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(198)

例如,如果我有这样的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int *ptr;

int
main(void)
{
 ptr = malloc(sizeof(int));
 if (ptr == NULL)
 return (1);
 if (fork() == 0) {
     (*ptr)++;
     printf("in child process\n");
     printf("%d\n", *ptr);
}
 (*ptr)++;
 printf("%d\n", *ptr);
 return (0);
}

我想知道当子进程启动并复制内存时,是指针ptr的副本被创建,还是它指向的实际内存也被复制。简而言之,我想知道是否会发生datarace,在孩子和父母之间,或者每个人都有一个指向内存中不同位置的指针ptr的不同副本,或者每个人都有一个指向内存中相同位置的指针的不同副本。
想知道当我使用指针存储变量时会发生什么,

jhdbpxl9

jhdbpxl91#

这不会导致比赛。fork()创建一个新进程(不是线程),并拥有所有变量的副本。从手册页:
fork()创建一个新进程。新进程(子进程)是调用进程(父进程)的精确副本,但以下情况除外:

•   The child process has a unique process ID.

       •   The child process has a different parent process ID (i.e., the
           process ID of the parent process).

       •   The child process has its own copy of the parent's descriptors.
           These descriptors reference the same underlying objects, so
           that, for instance, file pointers in file objects are shared
           between the child and the parent, so that an lseek(2) on a
           descriptor in the child process can affect a subsequent read or
           write by the parent.  This descriptor copying is also used by
           the shell to establish standard input and output for newly
           created processes as well as to set up pipes.

       •   The child processes resource utilizations are set to 0; see
           setrlimit(2).

请注意,(*ptr)++;会导致UB,因为ptr指向未初始化的内存。

相关问题