Ubuntu Semaphore: Segmentation fault (core dumped)

狂风中的少年 提交于 2020-01-16 21:55:11

问题


I am learning semaphores in C using Ubuntu right now. The professor just throw us this code and ask us to study it and observe. When I compiled I get a warning that ctime(&sem_buf.sem_ctime) returns an int, not a char * but nothing major. When I run it the output is just: Semaphore identifier: 0 Segmentation fault (core dumped). I am very confused as of what went wrong and I have no idea what is going on in this code. Some help would be very much appreciated.

Here is the code:

#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); 
   } 
} 

回答1:


You need to include time.h to the compiler recognize ctime function. The warning is because the compiler don't know ctime is a function and that returns an char*. By default GCC assumes the unknown function returns an int.



来源:https://stackoverflow.com/questions/33641068/ubuntu-semaphore-segmentation-fault-core-dumped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!