2012-03-02 2 views
0

아버지와 아이들을 동기화하려고하는데 다음 코드가 작동하지 않습니다 (분명히 usr_interrupt ++는 원자가 아님). 세마포어도 도움이되지 않는 것 같습니다.sigsuspend 교착 상태

#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <cstdlib> 
#include <iostream> 
#include <unistd.h> 
#include <cstring> 
#include <string> 
#include <semaphore.h> 
#include <fcntl.h> 

using namespace std; 

/* When a SIGUSR1 signal arrives, set this variable. */ 
volatile sig_atomic_t usr_interrupt; 
sem_t *mutex; 
char* SEM_NAME; 

void 
synch_signal (int sig) 
{ 
    // sem_wait(mutex); 
    usr_interrupt++; 
    // sem_post(mutex); 
} 

/* The child process executes this function. */ 
void 
child_function (void) 
{ 

    /* Perform initialization. */ 
    cerr << "I'm here!!! My pid is " << (int)getpid() << " my usr_int=" << usr_interrupt << endl; 
    /* Let parent know you're done. */ 
    kill (getppid(), SIGUSR1); 
    /* Continue with execution. */ 
    cerr << "Bye, now...." << endl; 
    exit(0); 
} 

int 
main (void) 
{ 
    usr_interrupt = 0; 

    string s_sem_name = "lir"; 
    SEM_NAME = new char[s_sem_name.size()+1]; 
    memcpy(SEM_NAME, s_sem_name.c_str(), s_sem_name.size()); 
    SEM_NAME[s_sem_name.size()] = '\0'; 
    mutex = sem_open (SEM_NAME,O_CREAT,0644,1); 
    if(mutex == SEM_FAILED) { 
    perror("unable to create semaphore"); 
    sem_unlink(SEM_NAME); 
    exit(-1); 
    } 


    struct sigaction usr_action; 
    sigset_t mask, oldmask; 
    pid_t child_id, child_id2; 

    /* Set up the mask of signals to temporarily block. */ 
    sigemptyset (&mask); 
    sigaddset (&mask, SIGUSR1); 

    /* Establish the signal handler.*/ 
    usr_action.sa_handler = synch_signal; 
    usr_action.sa_flags = 0; 
    sigaction (SIGUSR1, &usr_action, NULL); 

    /* Create the 2 children processes. */ 
    child_id = fork(); 
    if (child_id == 0) 
    child_function(); 

    child_id2 = fork(); 
    if (child_id2 == 0) 
    child_function(); 

    /* Wait for a signal to arrive. */ 
    sigprocmask (SIG_BLOCK, &mask, &oldmask); 
    while (usr_interrupt != 2) { 
    sigsuspend (&oldmask); 
    } 
    sigprocmask (SIG_UNBLOCK, &mask, NULL); 


    /* Now continue execution. */ 
    puts ("That's all, folks!"); 

    return 0; 
} 

누구든지 수정 제안을 제안 할 수 있습니까? (I 스레드를 사용할 수 없다) 베스트, - Liron 동일한 유형의

+0

AutoLocks를 사용하여 코드를 다시 작성하십시오. – AlexTheo

답변

1

You can't count signals. 두 신호는 입력 신호들 중 하나와 동일한 의미 론적 의미를 갖는다. USR1과 USR2와 같은 두 가지 신호 유형을 사용할 수 있습니다. 하지만 정직하게 말하면, 신호를 통신 메커니즘으로 사용해서는 안됩니다. 파이프처럼 감각적 인 것을 사용하십시오.

+0

David에게 감사드립니다. 그러나 아이가 다른 과정에 있다면 어떨까요? (예 : 포크 및 임원)? 또한, 나는 통신을위한 프로세스를 위해 메모리를 공유 했으므로 나는 단지 동기화 할 것을 원한다. –

+0

그러면 세마포어를 사용하십시오. 또는 명명 된 파이프를 사용하십시오. 또는 소켓. –