0
我正在使用Ubuntu學習C語言中的信號。教授只是拋出我們這段代碼,並要求我們研究並觀察。當我編譯時,我得到一個警告,ctime(&sem_buf.sem_ctime)
返回int
,而不是char *
,但沒有什麼重大。當我運行它時,輸出結果只是:Semaphore identifier: 0 Segmentation fault (core dumped)
。我很困惑,因爲出了什麼問題,我不知道這個代碼裏發生了什麼。一些幫助將非常感謝。Ubuntu Semaphore:細分故障(核心轉儲)
下面是代碼:
#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(「行%d \ n」,__LINE __)''語句。它會幫助我們大家找出哪裏出了問題。 –
你忘了'#include'這個警告肯定是主要的。 –
user3386109
添加'#include'使問題消失!謝謝。然而,信號標識符仍然是0,是否應該發生? –
Matt