C语言中如何使用turn变量进行同步?

发布于 2025-01-15 01:27:20 字数 1299 浏览 2 评论 0原文

我对信号量很陌生,我试图让我的子进程使用turn变量逐一执行代码,这意味着如果不是孩子的回合,它将不得不等待它的回合(当回合递增时)。我应该打印输出

I am child 0
0 1 2 3 4 5 6 7 8 9
I am child 1
10 11 12 13 14 15 16 17 18 19
etc.

但是当我运行代码时,它给了我一个分段错误,核心转储错误。有人可以帮忙吗?

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

#define NUM_PROCESSES 5

int main() {
    int i, j, pid;
    int *turn;
    int sharedid;
    //create a share memory region
    sharedid = shmget(IPC_PRIVATE, 4*sizeof(int), IPC_CREAT | 0600);
   //attach turn to the shared memory region
    turn = (int *) shmat(sharedid, NULL,0);
   // initialize it to 0
    *turn = 0;
    
    
    for(i=0; i<NUM_PROCESSES; i++) {
        if((pid = fork()) == 0) {
        
            break;
    }   
    }
    
    if(pid != 0) {
       while (*turn != i); 
       printf("I am child %d\n", i);

        for(j = i*10; j<i*10 + 10; j++){
            printf("%d ", j);
            fflush(stdout);
            usleep(250000);
        }

        printf("\n\n");
        *turn = *turn + 1;
          
    }
    else {
        for(i=0; i<NUM_PROCESSES; i++){ 
            wait(NULL);
        }
    shmdt(turn);
    shmctl(sharedid, IPC_RMID, 0);
          
    }
}

I am new to semaphore and I am trying to let my child process to execute the code one by one using the turn variable, which means that if it isnt the child's turn, it will have to wait for its turn (when turn increments). And I was supposed to print an output of

I am child 0
0 1 2 3 4 5 6 7 8 9
I am child 1
10 11 12 13 14 15 16 17 18 19
etc.

But when I run the code, it gave me a segmentation fault, core dumped error. Anyone can assist on this?

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

#define NUM_PROCESSES 5

int main() {
    int i, j, pid;
    int *turn;
    int sharedid;
    //create a share memory region
    sharedid = shmget(IPC_PRIVATE, 4*sizeof(int), IPC_CREAT | 0600);
   //attach turn to the shared memory region
    turn = (int *) shmat(sharedid, NULL,0);
   // initialize it to 0
    *turn = 0;
    
    
    for(i=0; i<NUM_PROCESSES; i++) {
        if((pid = fork()) == 0) {
        
            break;
    }   
    }
    
    if(pid != 0) {
       while (*turn != i); 
       printf("I am child %d\n", i);

        for(j = i*10; j<i*10 + 10; j++){
            printf("%d ", j);
            fflush(stdout);
            usleep(250000);
        }

        printf("\n\n");
        *turn = *turn + 1;
          
    }
    else {
        for(i=0; i<NUM_PROCESSES; i++){ 
            wait(NULL);
        }
    shmdt(turn);
    shmctl(sharedid, IPC_RMID, 0);
          
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文