程序使用内存段,等待锁访问数据段(基本)

时间:2012-06-07 18:09:55

标签: c sleep shared-memory

我必须说我知道信号量,但我还不知道如何使用它们。所以,当int lock获取特定值时,我将控制权传递给我的数据段,我怎么能让我的代码工作,因为此时它会冻结,我无法理解为什么......

s.c(服务器) - 首先运行

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include "st.h"

int main(){
    int shmid,i;
    int w =1;
    struct msg* m;
    shmid = shmget(1271,sizeof(struct msg), IPC_CREAT|IPC_EXCL|0600);

    if(shmid == -1){
        perror("~~~Shmid");
        exit(1);
    }   
    m = shmat(shmid,0,0);
    printf("segment attached to structure");

    do{
    printf("waiting...");
    sleep(1);
    }while(m->lock != 1);

    if(m->lock == 1)
    printf("lock open!");

    shmdt(m);
return 0;
}

C.C(客户端)

int main(int argc, char *argv[]){
    if(argc != 2)
        perror("~~~ ./c [file name]");
        exit(1);
    int shmid;
    struct msg* m;
    shmid = shmget(1271,0,0);

    if(shmid == -1){
        perror("~~~Shmid");
        exit(1);
    }   
    m = shmat(shmid,0,0);

    m->f = *argv[1];
    m->lock = 1;

    shmdt(m);
return 0;
}

st.h

struct msg{
    char f[50];
    int lock;   
};

2 个答案:

答案 0 :(得分:1)

错误在于客户端代码的开头:

int main(int argc, char *argv[]){
    if(argc != 2)
        perror("~~~ ./c [file name]");
        exit(1);
    int shmid;
    ...

您应该将perror()exit()语句放在大括号内。

在当前代码中,始终调用exit语句,并且客户端终止而不附加到内存块并更改锁定值。

答案 1 :(得分:0)

应该是:

data = shmat(shmid, (void *)0, 0); // note pointer
if (data == (char *)(-1))
    perror("shmat");
相关问题