全局变量在C中神奇地改变了值

时间:2012-12-15 22:35:06

标签: c global-variables

这可能需要一些调查,但我的问题很简单:

为什么numPassenger函数中parentHandler2()始终为0?

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
#include <signal.h>
#include <sys/time.h>
#include <math.h>

int getRand()
{
  return (rand() % 5001);
}

//////////GLOBAL//////////

const int CAPACITY = 100;
const int MEMSIZE = 1024;

char* sharedmem;

pid_t pid;

int numPassenger;
int numTram;

//////////GLOBAL//////////

//handles SIGALRM, generates passengers, sends SIGUSR1
void parentHandler1()
{
    numPassenger = getRand();
    sprintf(sharedmem, "%d", numPassenger);
    kill(getpid(), SIGUSR1);
}

//handles SIGUSR1, calculates number of trams needed, sends SIGUSR2
void childHandler()
{
    double n = atoi(sharedmem);
    numTram = (ceil(n/100));
    sprintf(sharedmem, "%d", numTram);
    kill(pid, SIGUSR2);
}

//outputs
void parentHandler2()
{
    int n = atoi(sharedmem);
    printf("Passengers: %d, Trams: %d\n", numPassenger, n);
}

int main (int argc, char* argv[])
{
    srand(time(0));

    key_t key;
    int shmemaddr;

    //shared memory
    key=ftok(argv[0],1);
    shmemaddr=shmget(key,MEMSIZE,IPC_CREAT|S_IRUSR|S_IWUSR);
    sharedmem = shmat(shmemaddr,NULL,0);

    pid = fork();
    if ( pid > 0 )
    {
        //timer
        struct itimerval timer;
        timer.it_value.tv_sec = 3; 
        timer.it_value.tv_usec = 0; 
        timer.it_interval.tv_sec = 3;
        timer.it_interval.tv_usec = 0;  
        setitimer (ITIMER_REAL, &timer, NULL);

        signal(SIGALRM, parentHandler1);
        signal(SIGUSR1, childHandler);
    }
    else if ( pid == 0 )
    {
        signal(SIGUSR2, parentHandler2);
    }

    //not so busy waiting
    while(1) sleep(1);

   return 0;
}

https://gist.github.com/4299915

1 个答案:

答案 0 :(得分:4)

Fork创建当前进程的新副本。全局变量不在进程之间共享。两个进程之间共享的唯一内存是shmget返回的内存。永远不会在子进程中设置numPassenger的值。