我有一个父程序,它将 fork 以下子程序并递增、显示、递减并显示变量“test”(最初为 0)15 次。我尝试运行它很多次,看看每隔几行后得到什么输出,但是我无法知道我的“测试”变量如何只显示零次、15 次。
//Include required preprocessors
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#define SHARED_MEM 1024 //shared memory size
int main(void)
{
/* The child process' new program. This program replaces the parent's */
/* program when 'fork()' is called */
printf("Process[%d]: child in execution ... \n",getpid());
int MAX = 15;
int shmID, shmID2;
key_t key = 1234, key2 = 2345;
int *test, *counter;
shmID = shmget(key, SHARED_MEM, 0666);
printf("\nShmID: %d", shmID);
shmID2 = shmget(key2, SHARED_MEM, 0666);
printf("\nshmID2: %d", shmID2);
test = (int *) shmat(shmID, 0, 0);
counter = (int *) shmat(shmID2, 0, 0);
printf("\ntEST before assignment: %d", *test);
printf("\nCounter: %d", *counter);
*test = 0;
*counter = 1;
printf("\ntest: %d", *test);
printf("\nCounter%d", *counter);
printf("\nAlmost there...");
if (*counter == 1){
for(int i=0; i < MAX; i++){
printf("\MAX: %d", MAX);
printf("%d", *test);
*test++;
}
*counter++; //to enter second condition of second child process
printf("\nCounter: %d", counter);
}
else if(*counter == 2){
for(int j = 0; j < MAX; j++){
printf("%d", *test);
*test++;
}
*counter--;
}
sleep(1);
printf("Process[%d]: child terminating ... \n", getpid());
shmdt(test);
shmdt(counter);
return 0;
}
最佳答案
我可以看到一些东西。
与代码的结构无关,我会检查 shmget 和 shmat 中是否存在错误: 我会改变
shmID = shmget(key, SHARED_MEM, 0666) shmID2 = shmget(key2, SHARED_MEM, 0666);
由
if ( (shmID = shmget(key, SHARED_MEM, 0666)) < 0)
{
perror("shmget");
exit(1);
}
if ( (shmID2 = shmget(key2, SHARED_MEM, 0666) < 0)
{
perror("shmat");
exit(1);
}
<小时/>
- 请注意,您正在使用
0666
创建 SHM特权但没有IPC_CREAT | IPC_EXCL
。 我建议您第一次创建时使用IPC_CREAT | IPC_EXCL | 0666
旗帜。
- 与第一点相同,我还将检查 shmat 的问题:
参见 test
的示例。 counter
应该是相同的.
if ((test = (int *) shmat(shmID, 0, 0)) == -1)
{
perror("shmat");
exit(1);
}
<小时/>
您可以使用命令ipcs
在cli中检查shm是否有问题,例如已经创建的shm。检查或ipcrm shm
删除并重新初始化:
ipcs shm | grep [your_shm_key or shmid]
关于c - 将零输入输出作为共享内存变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49978401/