我正在写一个C程序,我正在向n个玩家发牌,由n个分叉进程代表。我希望他们共享同一副牌,所以我试图使用mmap()
来跟踪牌组大小,但我必须编译此程序的机器不允许MAP_ANONYMOUS
或MAP_ANON
。还有另一种方法可以将全局变量存储在仍然符合C89 / pre Linux 2.4的共享内存中吗?
我的上下文程序:
static int *deck_size;
int pop(int *arr, int *size, int loc)
{
int i;
int val = arr[loc];
for(i = loc; i < (*size - 1); i++)
{
arr[i] = arr[(i+1)];
arr[*size] = '\0';
}
*size = *size-1;
return val;
}
int main(int argc, char* argv[])
{
pid_t pid, wpid;
int status, index, players, rdm_card;
char outbuf[100];
int deck[] =
{1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13};
deck_size = mmap(NULL, sizeof *deck_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*deck_size = 52;
/* reject an execution with no arguments */
if(argv[1] == NULL)
{
write(STDERR_FILENO, "Usage: dealer <n>\n", 18);
exit(EXIT_FAILURE);
}
else
{
if( (players = atoi(argv[1])) < 1)
{
write(STDERR_FILENO, "n cannot be less than 1\n", 24);
exit(EXIT_FAILURE);
}
}
srand ( time(NULL) );
rdm_card = rand() % *deck_size;
for(index = 0; index < players; index++)
{
pid = fork();
if (pid == 0) {
sprintf(outbuf, "random card: %d\n", pop(deck, deck_size, rdm_card));
write(STDOUT_FILENO, outbuf, 17);
printf("size of deck %d!\n", *deck_size);
exit(EXIT_SUCCESS);
} else if (pid < 0) {
write(STDERR_FILENO, "fork error\n", 11);
exit(EXIT_FAILURE);
} else {
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
return 0;
}
答案 0 :(得分:1)
当您清楚地阅读手册页MMAP(2)时,它清楚地表明自Linux内核2.4以来支持MAP_ANONYMOUS
。
使用 支持MAP_ANONYMOUS与MAP_SHARED一起使用 Linux仅从内核2.4开始。
请务必定义_BSD_SOURCE
或_SVID_SOURCE
以获取MAP_ANONYMOUS
#define _BSD_SOURCE