gpt4 book ai didi

c - 操作系统 - 进程

转载 作者:行者123 更新时间:2023-11-30 17:55:21 28 4
gpt4 key购买 nike

考虑这两个程序:

 //in  
#define MAX 50
int main(int argc, char* argv[]) {
int *count;
int fd=shm_open("/count",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
int ret=ftruncate(fd,sizeof(int));
count=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

while ((*count)==MAX);
(*count)++;
}

//out
int main(int argc, char* argv[]) {
int *count;
int fd=shm_open("/count",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
int ret=ftruncate(fd,sizeof(int));

count=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

(*count)--;
}

我有两个问题:

1)为什么这个程序不能正常运行(不能保证计数的数量永远不会超过50)?

2)我怎样才能纠正这两个程序来做到这一点?

谢谢。

最佳答案

你确定你想做:

while((*count)==MAX); // semicolon ?

而不是

    while(*count==MAX)
(*count)++;

还要检查 mmap 的返回值,它可能会失败。

关于c - 操作系统 - 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14418831/

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