【问题标题】:Operative systems, fork, shared memory and semaphore操作系统、fork、共享内存和信号量
【发布时间】:2013-07-23 17:12:46
【问题描述】:

我正在做作业,这是赛道:

命令行给出2个数字:argv[1] = 儿子数(n),argv[0] = 变量(m) 父亲生成 n 个儿子并创建共享内存段。然后等到儿子们结束工作。

儿子们使用信号量来修改必须写入和更新到共享内存中的变量 m。

当儿子结束时,父亲打印出变量 m 中包含的值。

这是新代码:

[代码]

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

struct shared {  // shared structure
   sem_t sem;
   int m;
};

void error(char *msg) {  // debug function
    pritnf("%s error.\n");
    return 1;
}

int main(int argc, char *argv[]) {

    int sid;    // segment id
    struct shared *data;    
    pid_t pid;

    if(argc<3) error("argc");

    if(argv[1]<0) error("argv");

    if(sid = shmget(IPC_PRIVATE, sizeof(shared *data),0666)<0) error("sid-shmget"); // father create sid

    if(data = (struct shared*) shmat(sid,(void *)0,1)<0) error("data-shmat"); // father allocate structure into his address scope

    data.m = argv[2]; // father initialize m

    if(sem_init(&data.sem)<0) error("sem_init"); // father initialize semaphore

    for (int i=0; i<atoi(argv[1]);i++) {  // create sons
        if((pid = fork())<0) error("fork");
    }

    if (pid>0) {  // father
        wait(NULL);  // wait for sons
        sem_wait(&data.sem);  // entry section
        printf("valore: %d\n", data.m);
        sem_post(&data.sem);  // exit section

    } else {  // son
        if(data = (struct shared*) shmat(sid,(void *)0,1)<0) error("shmat"); // son allocate data into his address scope

        sem_wait(data.sem); // entry section

                if (data.m%2 != 0) data.m*=2;  // modify variable
        else data.m-=1;

                sem_post(&data.m);  // exit section
        }

    shmdt(&data); // father and sons deallocate data

    if (pid>0) {  // father delete semaphore and sid
        sem_delete(&data.sem);
        shmctl(sid,IPC_RMID,0);
    }

return 0;
}

[/代码]

你怎么看?提前谢谢你

【问题讨论】:

  • argv[0] 将给出可执行文件的名称!!

标签: c fork shared-memory semaphore pid


【解决方案1】:

This This 将帮助您使用信号量和共享内存

【讨论】:

    【解决方案2】:

    您必须将共享变量放在共享内存中。一种方法是让它成为指向共享内存中某处的指针:

    int *m;
    
    /* ... */
    
    /* In the first process... */
    m = (int *) shared_memory;
    *m = 5;  /* Initialize `m` to the value `5` */
    
    /* In the second process... */
    m = (int *) shared_memory;
    *m += 10;  /* Add `10` to the shared variable `m` */
    
    /* Back in the first process */
    printf("%d\n", *m);  /* Will print `15` */
    

    您需要信号量来防止同时访问共享内存。

    【讨论】:

    • 谢谢,那么[CODE]m = (*int) shared memory;[/CODE]是我需要把变量m放到共享内存里面的代码吗?如何将信号量放在 shared_memory 中?
    • @user2611556 你可以用sem_open创建一个命名信号量,然后它就会被共享。
    • 我们没有在课上学习 sem_open。我只能使用我上面写的那种功能..
    • 好的,我管理了一下。我更新了第一个主题的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多