使用C语言中的POSIX无法将整数从一个进程发送到另一个进程

3
我是一名有用的助手,可以为您翻译文本。
我正在使用Linux上的GCC编译器和C语言。我有两个进程,并且我想将整数从一个进程传递到另一个进程,即从外部进程传递到中央进程,然后中央进程应该打印它。但我的代码不起作用。有人能告诉我如何纠正它吗?
这是我的代码:
central.c
#include<sys/types.h>
#include<sys/ipc.h>  
#include<sys/msg.h>
#include<stdio.h>

#define MsgKey 2345

typedef struct data_struct
{
    int  temp;
}data;

void main(void)
{
    data temp_msg;
    int msgqid;

if(msgqid=msgget(MsgKey, 0600 | IPC_CREAT)<0)
{
        printf("From Central Process: Msg queue failed");
}

msgrcv(msgqid,&temp_msg,sizeof(temp_msg),2,0);
printf("Value  = %d\n",temp_msg.temp);

printf("Central process exiting\n");
}

external.c

#include<sys/types.h> 
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>

#define MsgKey 2345

typedef struct data_struct
{  
    int  temp;
}data;

void main(void)
{
    data temp_msg;
    int msgqid;

        temp_msg.temp=5;

if(msgqid=msgget(MsgKey, 0600 | IPC_CREAT)<0)
{
        printf("From External Process: Msg queue failed");
}

if(msgsnd(msgqid,&temp_msg,sizeof(temp_msg),0)<0)
{
    printf("Error");
}
printf("External process exiting\n");
}

然后在终端上我输入了以下内容:

gcc -o central central.c
gcc -o external external.c
./central &
./external

我收到了"External process exiting"的错误提示,即使外部进程已经终止,中央进程仍在后台运行。

你应该使用 int main(void) 而不是 void main(void) - ashgkwd
2个回答

1
你传递给 msgsnd() 的结构不符合所需的格式要求:
struct msgbuf {
    long mtype;
    ...
};

因此,temp 字段可能被解释为消息类型,导致意外结果。
我的建议是避免使用 POSIX 消息队列。如果需要进程间通信,请使用套接字。它们更简单易用,并且具有网络透明性。

1

来自 POSIX 文档的 msgsnd

The application shall ensure that the argument msgp points to a user-defined buffer that contains first a field of type long specifying the type of the message, and then a data portion that holds the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:

struct mymsg {
    long   mtype;       /* Message type. */
    char   mtext[1];    /* Message text. */
}
你没有理解,所以你的代码无法工作。在你的结构体开头添加一个long字段,并将其设置为2,因为这是你的接收方期望的消息类型。
还需要将该结构体定义移动到头文件中,以便在两个代码之间共享,而不是重复定义。
 if(msgqid=msgget(MsgKey, 0600 | IPC_CREAT)<0)

在这两个代码片段中,在赋值语句周围加上括号:
 if((msgqid=msgget(MsgKey, 0600 | IPC_CREAT)) < 0)

< 和其他比较运算符的优先级高于赋值运算符,因此如果没有括号,您的代码是不正确的 - 它将比较的结果分配给msgqid

最后,main函数返回一个int,而不是void


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接