gpt4 book ai didi

c - 使用消息队列的多进程通信

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:49 24 4
gpt4 key购买 nike

我正在尝试实现类似于此示例的程序:

程序在4个进程之间传递一个整数,每个进程递减该整数

每个进程都有自己的邮箱

每个进程检查其邮箱中的变量“counter”,如果找到则将其递减

然后它将计数器变量发送给下一个进程

但是程序中有一个错误,我找不到它。请注意,这是一项作业,我只是在寻找可以帮助我找到错误的提示。

enter image description here

typedef struct {
int counter;
char data[256];
int id; //id of the process that previously decremented the counter
} msg;



int main(int arqc, char *argv[]){
int key=9;
int id=0;
pid_t pid;
int num=5;
int i, k;
int arr[5];


//create 5 forks
if (arqc != 2){
num=5;
}else{
int ret = sscanf(argv[1], "%d", &num);
if (ret != 1)return 0;
}
for(i=0 ; i<num ; i++){
if ((pid = fork()) == -1) {
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
if (pid == 0) {
id=i;
}
else {
break;
}
}



//process 1 to n comes here
msg m;
int boxid = msgget(id, 0600 | IPC_CREAT);
arr[id]=boxid;
int firstRun=1;

//initiate the first move
if((id==0)&&(firstRun==1)){
m.counter = INIT_COUNTER;

//send msg to next process
msgsnd(arr[id], &m, sizeof(msg), 0); //send msg to own inbox
firstRun=0;
}



while(1){
//check inbox of current process
int rec = msgrcv(arr[id], &m, sizeof(msg), 0, 0);

printf("Im %d, counter is %d, rec is %d\n",id, m.counter, rec);


int index;
if(id==num){
index=0;
}else{
index=id+1;
}

//send message to the next inbox
int sent = msgsnd(arr[index], &m, sizeof(m), 0);

printf( "Error opening file: %s\n", strerror( errno ) );

sleep(1);
}

}

最佳答案

您的初始 msgsnd 因参数无效而失败,并且所有内容都从那里开始。

SysV 消息队列需要消息类型字段作为消息中的第一个字段,因此您需要执行类似的操作。

typedef struct
{
long int mtype;
int counter;
char data[256];
int id; //id of the process that previously decremented the counter
} msg;

在发送之前,您还必须设置消息内容并设置正确的长度。

//initiate the first move
if ((id == 0) && (firstRun == 1))
{
m.mtype = 100;
m.counter = INIT_COUNTER;
strncpy(m.data, "some kind of message is nice", sizeof(m.data));
m.id = id;

size_t msgsize = sizeof(msg) - sizeof(long int);

//send msg to next process
int sent = msgsnd(arr[id], &m, msgsize, 0); //send msg to own inbox

if (sent == -1)
{
perror("msgsend");
exit(1);
}

firstRun = 0;
}

您会遇到超出此范围的问题(例如,在 msgrcv 上设置正确的大小)但这应该可以帮助您克服最初的困难。

关于c - 使用消息队列的多进程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19531484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com