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



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

为什么numPassengerparentHandler2()函数中总是 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: %dn", 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

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

相关内容

  • 没有找到相关文章

最新更新