【发布时间】:2015-11-10 22:43:18
【问题描述】:
我现在正在使用 Ubuntu 学习 C 中的信号量。教授只是把这段代码扔给我们,让我们研究和观察。当我编译时,我收到一个警告,ctime(&sem_buf.sem_ctime) 返回一个int,而不是char *,但没什么大不了的。当我运行它时,输出只是:Semaphore identifier: 0 Segmentation fault (core dumped)。我对出了什么问题感到非常困惑,我不知道这段代码发生了什么。非常感谢您的帮助。
代码如下:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
# define NS 3
union semun {
int val;
struct semid_ds *buf;
ushort *array; // Unsigned short integer.
};
int main(void)
{
int sem_id, sem_value, i;
key_t ipc_key;
struct semid_ds sem_buf;
static ushort sem_array[NS] = {3, 1, 4};
union semun arg;
ipc_key = ftok(".", 'S'); // Creating the key.
/* Create semaphore */
if ((sem_id = semget(ipc_key, NS, IPC_CREAT | 0666)) == -1) {
perror ("semget: IPC | 0666");
exit(1);
}
printf ("Semaphore identifier %d\n", sem_id);
/* Set arg (the union) to the address of the storage location for */
/* returned semid_ds value */
arg.buf = &sem_buf;
if (semctl(sem_id, 0, IPC_STAT, arg) == -1) {
perror ("semctl: IPC_STAT");
exit(2);
}
printf ("Create %s", ctime(&sem_buf.sem_ctime));
/* Set arg (the union) to the address of the initializing vector */
arg.array = sem_array;
if (semctl(sem_id, 0, SETALL, arg) == -1) {
perror("semctl: SETALL");
exit(3);
}
for (i=0; i<NS; ++i) {
if ((sem_value = semctl(sem_id, i, GETVAL, 0)) == -1) {
perror("semctl : GETVAL");
exit(4);
}
printf ("Semaphore %d has value of %d\n",i, sem_value);
}
/*remove semaphore */
if (semctl(sem_id, 0, IPC_RMID, 0) == -1) {
perror ("semctl: IPC_RMID");
exit(5);
}
}
【问题讨论】:
-
您是否确定了发生异常的行?如果没有,您可以尝试使用调试器,或者在周围散布一些
printf("line %d\n", __LINE__);语句。这将帮助我们所有人找出问题所在。 -
你忘了
#include <time.h>,这个警告肯定很严重。 -
添加
#include <time.h>让问题消失了!谢谢你。但是信号量标识符仍然是 0,这应该发生吗? -
如有疑问,请阅读man page:“成功时返回有效的段标识符shmid,错误时返回-1。”
-
0是一个有效的 ipc id,最有可能在重新启动系统后。
标签: c pointers ubuntu semaphore