我有一个父程序,它将分叉以下子程序并递增,显示,减少并显示变量'test'(最初为0)15次。我尝试运行它很多次,看看每几行之后我得到了什么输出,但是我无法知道我的'test'变量如何只显示零,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;
}
我可以看到几件事。
通过
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
标志创建。请参阅test
的示例。 counter
应该是一样的。
if ((test = (int *) shmat(shmID, 0, 0)) == -1)
{
perror("shmat");
exit(1);
}
你可以检查cli是否有什么问题shm,例如,已经创建,使用命令ipcs
检查或ipcrm shm
删除并重新初始化:
ipcs shm | grep [your_shm_key or shmid]