[英]Semaphore cleanup in Linux c
When I create a shared memory (c program in Linux) I delete it with shmctl(shmid, IPC_RMID, 0)
and everything looks fine when I'm using ipcs -m
to check if there are any remaining shared memory segments.当我创建共享 memory (Linux 中的 c 程序)时,我使用shmctl(shmid, IPC_RMID, 0)
将其删除,当我使用ipcs -m
检查是否还有剩余的共享 memory 段时,一切看起来都很好。 But I'm wondering how can I delete my semaphores that I've created right before the program is terminated because when I'm using ipcs -s
I see both of my semaphores right there, result:但是我想知道如何在程序终止之前删除我创建的信号量,因为当我使用ipcs -s
时,我看到我的两个信号量都在那里,结果:
------ Semaphore Arrays --------
key semid owner perms nsems
0x6b014021 0 benjamin 600 1
0x6c014021 1 benjamin 600 1
Thanks.谢谢。
You can use semget
and semctl
after setting KEY to the right value returned by ipcs -s
:在将 KEY 设置为ipcs -s
返回的正确值后,您可以使用semget
和semctl
:
#define KEY 0x...
int id, rc;
id = semget(KEY, 1, IPC_STAT);
if (id < 0)
{
perror("semget");
exit(1);
}
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
Or use directly semctl
with id returned by ipcs -s
:或者直接使用semctl
和ipcs -s
返回的 id :
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
Full C program:完整的 C 程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <errno.h>
int main(int argc, char **argv){
int id, rc;
id = atoi(argv[1]);
printf("id=%d\n", id);
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
exit(0);
}
Execution:执行:
$ ipcs -s
------ Tableaux de sémaphores --------
clef semid propriétaire perms nsems
0x00001111 393221 pifor 666 1
$ ./rsem 393221
id=393221
$ ipcs -s
------ Tableaux de sémaphores --------
clef semid propriétaire perms nsems
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.