gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:48 26 4
gpt4 key购买 nike

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

为什么 parentHandler2() 函数中的 numPassenger 总是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com