user11432153
user11432153

Reputation:

Running a program with semaphores

I have this program from the official geeks4geeks site which uses semaphors between 2 threads:

// C program to demonstrate working of Semaphores 
#include <stdio.h> 
#include <pthread.h> 
#include <semaphore.h> 
#include <unistd.h> 

sem_t mutex; 

void* thread(void* arg) 
{ 
    //wait 
    sem_wait(&mutex); 
    printf("\nEntered..\n"); 

    //critical section 
    sleep(4); 

    //signal 
    printf("\nJust Exiting...\n"); 
    sem_post(&mutex); 
} 


int main() 
{ 
    sem_init(&mutex, 0, 1); 
    pthread_t t1,t2; 
    pthread_create(&t1,NULL,thread,NULL); 
    sleep(2); 
    pthread_create(&t2,NULL,thread,NULL); 
    pthread_join(t1,NULL); 
    pthread_join(t2,NULL); 
    sem_destroy(&mutex); 
    return 0; 
} 

According to this site running it will print this result:

Entered..

Just Exiting...

Entered..

Just Exiting...

In my computer in ubuntu linux i compile it using gcc main.c -lpthread -lrt and it compiles succesfully but after that trying to run it with ./main.c gives me these error:

./main.c: line 8: sem_t: command not found
./main.c: line 10: syntax error near unexpected token `('
./main.c: line 10: `void* thread(void* arg)'

Should i run it with a different command or am i missing something else here?Please help.

Upvotes: 1

Views: 7436

Answers (2)

rmwu
rmwu

Reputation: 51

After compiling your code, you should have a file called a.out, which is the executable. Run it with ./a.out. You can give the executable another name with the option -o <name>. Anyway, check man gcc for further information. The full command to compile your code is

gcc main.c -o main -lpthread -lrt

Upvotes: 3

VonC
VonC

Reputation: 1323363

./main.c should not be the command you run.

After compilation, you should get an executable that you do run, not the source file.

Upvotes: 1

Related Questions