这可能需要一些调查,但我的问题很简单:
为什么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

最佳答案

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

关于c - 全局变量在C中神奇地更改值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13896825/

10-09 15:33