C语言中如何使用turn变量进行同步?
我对信号量很陌生,我试图让我的子进程使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论