开发者

Why semop() hangs?

开发者 https://www.devze.com 2023-02-01 04:11 出处:网络
When trying run this code: At first it prints \"Process some_id BEFORE enter\" for each semaphor (2 times). Then it hangs. What is incorrect?

When trying run this code: At first it prints "Process some_id BEFORE enter" for each semaphor (2 times). Then it hangs. What is incorrect?

# include <sys/ipc.h>
# include <sys/sem.h>
# include <unistd.h>
# include <errno.h>
# include <stdio.h>
# include <stdlib.h>
# include <iostream>

int seminit()
{
    key_t key = ftok("/bin", 1);
    int semid = semget (key, 1, IPC_CREAT | IPC_EXCL | 600);
    if(-1 == semid)
        if(EEXIST == errno)
            semid = semget(key, 1, 0);
    return semid;
}

void uninit(int semid)
{
        semctl(semid, 0, IPC_RMID);
}

void semlock(int semid)
{
    struct sembuf p_buf;
    p_buf.sem_num = 0;
    p_buf.sem_op = -1;
    p_buf.sem_flg = SEM_UNDO;
    if(semop(semid, &p_buf, 1) == -1)
        printf("semlock failed: ERRNO: %d\n", errno);
}
void semunlock(int semid)
{
    struct sembuf v_b开发者_运维知识库uf;
    v_buf.sem_num = 0;
    v_buf.sem_op = 1;
    v_buf.sem_flg = SEM_UNDO;
    if(semop(semid, &v_buf, 1) == -1)
        printf("semunlock failed: ERRNO: %d\n", errno);
}
void some_function()
{
    int semid = seminit();
    pid_t pid = getpid();
    printf("Process %d BEFORE enter\n", pid);
    semlock(semid);
    printf("Process %d IN Critical section\n", pid);
    sleep(10);
    semunlock(semid);
    printf("Process %d AFTER leave\n", pid);
    uninit(semid);
}

int main(int argc, char** argv) 
{
    for(int i = 0; i < 2; ++i)
        if(0 == fork())
            some_function();
    return (EXIT_SUCCESS);
}


Seems that only a child is generated (I think that is not intended), still, I believe there is a missing wait before the return of the main process, which means that the main process will end faster than the child process and let it "hanged" (this can be part of the issue but is not maybe the hole issue, check that for cycle before).

0

精彩评论

暂无评论...
验证码 换一张
取 消