1

I need to resume after calling pause(), from what I read of the manual, it should resume after it receives a signal, but apparently is not working for me, also I'm using a semaphore to make sure that the program register the signal handler before I send the signal to resume it

void child(){
    fprintf(stdout,"Hello!\n");
    exit(0);
}

int main(int argc, char **argv){
    sem_t sem;
    sem_init(&sem,0,0);
    int pid = fork();
    if(pid == 0){
        signal(SIGCONT, child);
        sem_post(&sem);
        pause();
    } else {
        sem_wait(&sem);
        kill(pid, SIGCONT);
        int status;
        waitpid(pid,&status, 0);
    }
    return EXIT_SUCCESS;
}

This is not the actual program that I'm working on, but it has the structure of it.

What is happening is that the parent hangs at waitpid() and the child never leaves the pause() call, I know this because it never prints the message "Hello!"

Andres Perez
  • 149
  • 15
  • If it's not working, what is happening? – Xymostech Dec 11 '13 at 03:53
  • I forgot to add that, thanks :) – Andres Perez Dec 11 '13 at 03:58
  • 1
    Check the return value of `sem_init`. Maybe unnamed semaphores aren't supported on your system. I've had this happen to me on OS X machines. Edit: Also, shouldn't your second argument be non-zero? " If the pshared argument has a non-zero value, then the semaphore is shared between processes; in this case, any process that can access the semaphore sem can use sem for performing sem_wait(), sem_trywait(), sem_post(), and sem_destroy() operations." – tangrs Dec 11 '13 at 04:02
  • From adding some print statements, it looks like it's not getting past the `sem_wait`, which agrees with what tangrs said. – Xymostech Dec 11 '13 at 04:04
  • I did 2 things, first I moved the semaphore to be a global variable, so it can be accessed and modified by the child thread, second I changed the value of pshared to 1 and check the value, and I see that is returning 0, so it is initializing correctly. Still don't know what I'm missing – Andres Perez Dec 11 '13 at 04:20

1 Answers1

2

It looks like you're actually falling victim to a failure in sharing the semaphore. If you follow the steps in this answer to put the semaphore in shared memory, then your program works fine:

#include <sys/mman.h>

...

sem_t *sem = mmap(NULL, sizeof(sem), 
    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
    -1, 0);

(and obviously replace the &sems with sem)

Community
  • 1
  • 1
Xymostech
  • 9,710
  • 3
  • 34
  • 44