天天看點

fork()後父子程序間的變量共享情況

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

int golobal_a = 0;

int main()
{
	int local_a = 0;
	pthread_mutex_t local_mutex_a;
	pthread_mutex_t local_mutex_b;
	pid_t pid;

	pthread_mutex_init(&local_mutex_a, NULL);
	pthread_mutex_init(&local_mutex_b, NULL);
	pid = fork();

	if(pid > 0) {
		printf("father %d, child %d\n", getpid(), pid);
		local_a = 1;
		golobal_a = 1;
		sleep(1);
		printf("father local_a %d, addr %p, golobal_a %d, addr %p\n", local_a, &local_a, golobal_a, &golobal_a);

		pthread_mutex_lock(&local_mutex_a);
		printf("father lock mutex a %p\n", &local_mutex_a);
		sleep(1);
		pthread_mutex_lock(&local_mutex_b);
		printf("father lock mutex b %p\n", &local_mutex_b);
		pthread_mutex_unlock(&local_mutex_b);
		pthread_mutex_unlock(&local_mutex_a);
	} else if (pid == 0) {
		printf("child %d\n", getpid());
		local_a = 2;
		golobal_a = 2;
		sleep(1);
		printf("child local_a %d, addr %p, golobal_a %d, addr %p\n", local_a, &local_a, golobal_a, &golobal_a);

		pthread_mutex_lock(&local_mutex_b);
		printf("child lock mutex b %p\n", &local_mutex_b);
		sleep(1);
		pthread_mutex_lock(&local_mutex_a);
		printf("child lock mutex a %p\n", &local_mutex_a);
		pthread_mutex_unlock(&local_mutex_a);
		pthread_mutex_unlock(&local_mutex_b);
	} else
		printf("fork fail\n");

	return 0;
}
           

輸出

father 17164, child 17165
child 17165
father local_a 1, addr 0x7fff1793d298, golobal_a 1, addr 0x601070
father lock mutex a 0x7fff1793d2a0
child local_a 2, addr 0x7fff1793d298, golobal_a 2, addr 0x601070
child lock mutex b 0x7fff1793d2d0
father lock mutex b 0x7fff1793d2d0
child lock mutex a 0x7fff1793d2a0
           

程式正常退出,沒有發生死鎖,說明不管是局部的還是全局的變量或者是鎖,fork()之後,子程序都擁有了一份父程序的拷貝。

雖然變量和鎖的虛拟位址都是一樣的,但是實體上是兩個不同的記憶體位址,兩個程序之間完全不受影響。

繼續閱讀