2015-11-10 70 views
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); 
    } 
} 
+0

您是否确定了发生异常的行?如果没有,你可以尝试使用一个调试器,或者在周围撒上一些'printf(“行%d \ n”,__LINE __)''语句。它会帮助我们大家找出哪里出了问题。 –

+5

你忘了'#include '这个警告肯定是主要的。 – user3386109

+0

添加'#include '使问题消失!谢谢。然而,信号标识符仍然是0,是否应该发生? – Matt

回答

0

您需要包括time.h编译器识别ctime功能。警告是因为编译器不知道ctime是一个函数,并且返回char*。默认情况下GCC假定未知函数返回一个int