Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7075695
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:12:29+00:00 2026-05-28T06:12:29+00:00

Possible Duplicate: sem_open() error: “undefined reference to sem_open()” on linux (Ubuntu 10.10) Having issues

  • 0

Possible Duplicate:
sem_open() error: “undefined reference to sem_open()” on linux (Ubuntu 10.10)

Having issues with compilation of posix semaphores. My goal is to create a shared memory segment and protect it by semaphores. shared memory works fine but semaphores code gives me compilation errors even though I included semaphore.h and added -lrt to compilation flags

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <time.h>


int main (int argc, char** argv) {
    FILE *configFile;
    int i,j;


    int CashDesksNo=0;
    int maxCashDesksNo;
    int n,m;
    int TmaxServe;
    int custPerc; //customer ratio policy
    int maxCapacity;


    char * nlptr=NULL;
    char * pch=NULL;
    char line[125];

    char termInput[30];
    char tmpString[40];

    int flg1,flg2;
    int flag;

    int execResult=0;
    int fd;
    int rc;

    int randNum;

    int status;
    pid_t ch_pid;

    int a,b,c;
    int shmid=0;
    int *shm_ptr;
    int * err;

    int retval;
    sem_t *sp;
    char semName[10];

    strcpy(semName,"mutex");
    //---------- Davasma kai elegxos in line parameters-----------------
        //    read inline params and config file    
                              .
                              .
                              .

    //------------ Print Configuration Data ----------------------------
    if(CashDesksNo>maxCashDesksNo || CashDesksNo<1)
    {
        printf("\n# of Cash Desks should be between 1 and %d",maxCashDesksNo);
        printf("\nsupermarket will now exit...\n");
        exit(1);
    }

    printf("\n//-----------------------------------------------");
    printf("\nSupermarket initialization");
    printf("\n# of Cash Desks: %d",CashDesksNo);
    printf("\n# of max products: %d",n);
    printf("\nMax price: %d",m);
    printf("\nMaximum serving time(secs): %d",TmaxServe);
    printf("\n%% Customer/Cashier Percentage: %d/%d",custPerc,100-custPerc);
    printf("\nMax Supermarket capacity: %d",maxCapacity);
    printf("\n//-----------------------------------------------\n");

    printf("\nAbout to create customer and cashier processes");

// ----------- Shared Memory Attachment --------------------------------
shmid=shmget(IPC_PRIVATE,sizeof(int*),0666); 

if (shmid < 0)
{
    perror("shmget");
    exit(1);
}

shm_ptr=(int*)shmat(shmid,(void *)0,0);

if (shm_ptr == (int *)(-1))
{
    perror("shmat");
    exit(1);
}

a=0;    //shm
shm_ptr=(int*)a;
printf("shmPtr:%d",(int)shm_ptr);



// ----- create & initialize semaphore ---------------------------------

  sp = sem_open(semName,O_CREAT,0644,1);
  if(sp == SEM_FAILED)
    {
      perror("unable to create semaphore");
      exit(-1);
    }


    while(1)
    {
        printf("\nPress enter to start a new day at the supermarket(type exit to quit)\n");
        fgets(termInput,sizeof(termInput),stdin);

        nlptr = strchr(termInput, '\n');// termatismos string
        if (nlptr) *nlptr = '\0';

        if(strcmp(termInput,"exit")==0)//exit apo tin efarmogi
        {
            printf("\nExiting Supermarket..\n");
            exit(0);
        }

        i=0;
        while(i<maxCapacity)
        {


            //-Fork new process for the simulation --------------------

            ch_pid = fork();

            if (ch_pid == -1) {
            perror("\nFailed to fork initial spliter/merger process  \n");
            exit(1);
            }


            if ( ch_pid == 0 ) //this is the child process
            {
            srand (getpid());//pid based seed

            // "itoa" - Metatropi ari8mou se string
            sprintf( tmpString, "%d", shmid );

            randNum=rand() % 100 + 1;
            if(randNum<custPerc)// customer : cashier ratio
            {
                execResult=execl("customer","customer","0",tmpString,NULL);
                //printf("\nCreated a customer,randNum %d",randNum);
            }else
            {
                execResult=execl("cashier","cashier","0",tmpString,NULL);
                //printf("\nCreated a cashier,randNum %d",randNum);

            }

                if(execResult==-1)
                {
                    perror("Could not perform exec to create cashier/customer process");
                }

            }
        i++;        
        }

        //Root process
        //wait for childs to terminate
                for (i = 0; i < maxCapacity; ++i) 
                {
                    waitpid(-1,&status,0);
                }
        printf("supermarket shared memory content: %d",(int)shm_ptr);
        sem_close(sp);
        sem_unlink(semName);

        err = (int*)shmctl(shmid, IPC_RMID, 0);
        if (err == -1) 
            perror ("Shared Memory Removal.");
        else 
            printf("Shared Memory Removed. %d\n", (int)(err));


    }



} 

this is the makefile:

OBJS    = supermarket.o cashier.o customer.o 
SOURCE  = supermarket.c cashier.c customer.c 
HEADER  = struct.h
OUT     = supermarket cashier customer
CC  = gcc
FLAGS   = -lrt -g -c 
LIBS    = -lm
# -g option enables debugging mode 
# -c flag generates object code for separate files
# -lm math library

all: supermarket cashier customer

supermarket: supermarket.c
    $(CC) supermarket.c -o supermarket

cashier: cashier.c
    $(CC) cashier.c -o cashier

customer: customer.c
    $(CC) customer.c -o customer


# clean house
clean:
    rm -f $(OBJS) $(OUT)

# do a bit of accounting
count:
    wc $(SOURCE) $(HEADER)

I keep getting this error:

george@george-System-Product-Name:~/Desktop/prj3$ make
gcc supermarket.c -o supermarket
supermarket.c: In function ‘main’:
supermarket.c:310:11: warning: comparison between pointer and integer [enabled by default]
/tmp/ccYxA2Wi.o: In function `main':
supermarket.c:(.text+0x75c): undefined reference to `sem_open'
supermarket.c:(.text+0x9b0): undefined reference to `sem_close'
supermarket.c:(.text+0x9bf): undefined reference to `sem_unlink'
collect2: ld returned 1 exit status
make: *** [supermarket] Error 1

what can i do?
this is a project for operating systems class, my system is linux Ubuntu

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:12:30+00:00Added an answer on May 28, 2026 at 6:12 am

    I think you should link against pthread as well:

    -lpthread
    

    Example makefile from an old project of mine (see comments):

    CC=gcc
    CFLAGS=-c -Wall -O3 -g
    LDFLAGS=-pthread
    SOURCES=chatzor.c clientlist.c messagequeue.c
    OBJECTS=$(SOURCES:.cpp=.o)
    EXECUTABLE=chatzor_server
    
    all: $(SOURCES) $(EXECUTABLE)
    
    $(EXECUTABLE): $(OBJECTS) 
        $(CC) $(LDFLAGS) $(OBJECTS) -o $@
    
    .cpp.o:
            $(CC) $(CFLAGS) $< -o $@
    
    clean:
        rm -rf *.o ${EXECUTABLE}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: git push error '[remote rejected] master -> master (branch is currently checked
Possible Duplicate: php == vs === operator Reference - What does this symbol mean
Possible Duplicate: How an uninitialised variable gets a garbage value? So when an undefined
Possible Duplicate: Interprocess semaphores sometimes not working as expected In my application, I notice
Possible Duplicate: Best way to determine if two path reference to same file in
Possible Duplicate: What are the stages of compilation of a C++ program? I find
Possible Duplicate: Why not use tables for layout in HTML? Under what conditions should
Possible Duplicate: NAnt or MSBuild, which one to choose and when? What is the
Possible Duplicate: How do I calculate someone's age in C#? Maybe this could be
Possible Duplicate: .NET - What’s the best way to implement a catch all exceptions

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.