这是一个技术问题,如果您了解C和UNIX(也许这是一个非常新手的问题,也许你可以帮助我!)
今天在我们的操作系统课程中分析一些代码时出现了一个问题.我们正在学习在UNIX中"分叉"一个进程意味着什么,我们已经知道它创建了与它并行的当前进程的副本,并且它们具有单独的数据部分.
但后来我认为,如果在执行fork()之前创建一个变量和一个指向它的指针,因为指针存储变量的内存地址,可以尝试通过子进程修改该变量的值.使用该指针.
我们在课堂上尝试了类似的代码:
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main (){
int value = 0;
int * pointer = &value;
int status;
pid_t pid;
printf("Parent: Initial value is %d\n",value);
pid = fork();
switch(pid){
case -1: //Error (maybe?)
printf("Fork error, WTF?\n");
exit(-1);
case 0: //Child process
printf("\tChild: I'll try to change the value\n\tChild: The pointer value is %p\n",pointer);
(*pointer) = 1;
printf("\tChild: I've set the value to %d\n",(*pointer));
exit(EXIT_SUCCESS);
break;
}
while(pid != wait(&status)); //Wait for the child process …Run Code Online (Sandbox Code Playgroud)