[英]Semaphore cleanup in Linux c
當我創建共享 memory (Linux 中的 c 程序)時,我使用shmctl(shmid, IPC_RMID, 0)
將其刪除,當我使用ipcs -m
檢查是否還有剩余的共享 memory 段時,一切看起來都很好。 但是我想知道如何在程序終止之前刪除我創建的信號量,因為當我使用ipcs -s
時,我看到我的兩個信號量都在那里,結果:
------ Semaphore Arrays --------
key semid owner perms nsems
0x6b014021 0 benjamin 600 1
0x6c014021 1 benjamin 600 1
謝謝。
在將 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);
}
或者直接使用semctl
和ipcs -s
返回的 id :
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
完整的 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);
}
執行:
$ 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.