Как переменные распределяются между двумя процессами, когда задействован форк

/*  In alarm.c, the first function, ding, simulates an alarm clock.  */

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

static int alarm_fired = 0;

void ding(int sig)
{
    alarm_fired = 1;
}

/*  In main, we tell the child process to wait for five seconds
    before sending a SIGALRM signal to its parent.  */

int main()
{
    pid_t pid;

    printf("alarm application starting\n");

    pid = fork();
    switch(pid) {
    case -1:
      /* Failure */
      perror("fork failed");
      exit(1);
    case 0:
      /* child */
        sleep(5);
        printf("getppid: %d\n", getppid());
        kill(getppid(), SIGALRM);
        exit(0);
    }

/*  The parent process arranges to catch SIGALRM with a call to signal
    and then waits for the inevitable.  */

    printf("waiting for alarm to go off\n");
    (void) signal(SIGALRM, ding);

    printf("pid: %d\n", getpid());
    pause();
    if (alarm_fired)
        printf("Ding!\n");

    printf("done\n");
    exit(0);
}

I have run the above code under Ubuntu 10.04 LTS

> user@ubuntu:~/Documents/./alarm
> alarm application starting
> waiting for alarm to go off
> pid: 3055
> getppid: 3055
> Ding!
> done

Я прочитал следующее утверждение из книги.

Важно четко понимать, разница между системой вилок вызов и создание новых потоков. Когда процесс выполняет вызов fork, создается новая копия процесса со своими переменными и собственными PID. Этот новый процесс запланирован самостоятельно и (в целом) выполняется практически независимо от процесс, который его создал.

Вопрос: Мне кажется, что переменная alarm_fired используется совместно исходным и новым созданным процессом.

Это правильно?

6
задан Fred Foo 5 July 2011 в 17:53
поделиться