Take the 2-minute tour ×

I have this code:

#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(){
    int segment_n;
    int segment_sem;
    int *shared_n;
    sem_t *shared_sem;
    int pid_int;
    pid_t pid;

    segment_n = shmget(IPC_PRIVATE, sizeof(int), S_IRUSR | S_IWUSR);
    segment_sem = shmget(IPC_PRIVATE, sizeof(sem_t), S_IRUSR | S_IWUSR);
    shared_n = (int *)shmat(segment_n, NULL, 0);
    shared_sem = (sem_t *)shmat(segment_sem, NULL, 0);

    sem_init(shared_sem, 0, 0);

    scanf("%d", shared_n);

    pid = fork();
    if(pid < 0){
        return 1;
    } else if(pid == 0){
    pid_int = (int)getpid();
    if(pid_int > *shared_n){
        *shared_n = 1;
        }else if(pid_int == *shared_n){
            *shared_n = 0;
        } else {
            *shared_n = -1;
        return 0;
    } else {
        printf("returns: %d\n", *shared_n);
        return 0;
    return 0;

The program creates a child process that verifies if the number in shared_n is >, < or == of his own pid, than writes in shared_n 1, -1 or 0 respectivly.

The problem is that when I compile it, it gives me this output: https://dl.dropboxusercontent.com/u/6701675/informatica/Istantanea%20-%2020062013%20-%2013%3A49%3A14.png

Thank in advance for your help!


share|improve this question
-pthread. Even if you don't use pthreads, you need the library to use the semaphore functions. Also, you need to create the semaphore with pshared != 0. –  Aneri Jun 20 '13 at 12:01
@Aneri yes!! thank you very much, This is the right answer! But where I could find that solution? I've searched everywhere in the net.. –  Lorenzo Barbagli Jun 20 '13 at 12:11
Google for say sem_init library, you will get this link linuxforums.org/forum/programming-scripting/… –  Aneri Jun 21 '13 at 6:09

2 Answers 2

up vote 0 down vote accepted

Is this Linux? The Linux manpage says you need to link with the pthread library.

gcc foo.c -o foo -pthread
share|improve this answer

You have to link the file with -pthread

"gcc -pthread processi_esame.c -o processi"

share|improve this answer

Your Answer


