[問題] 關於 msgget()用法 [已解決]
遇到的問題: (題意請描述清楚)
小弟最近在學 Linux 系統 的相關程式設計
書上一個範例 是透過兩個程式 msg_receiver.c msg_sender.c
一個呼叫 msgsnd() 一個呼叫 msgrcv() 來達成通訊的功能
可是程式最開始的地方呼叫 msgget() 就一直 失敗 = ="
希望得到的正確結果:
成功可以由 send 一方發送信息到 rec 一方
程式跑出來的錯誤結果:
msgget!: No such file or directory
開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
gcc
有問題的code: (請善用置底文標色功能)
if ((msgid = msgget((key_t)12345, 0666) | IPC_CREAT) == -1) {
perror("msgget!");
exit(EXIT_FAILURE);
}
//呼叫 msgget() 的方法,我兩邊用的 code 一樣的
補充說明:
完整的 code
//= msg_sender.c =======================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
typedef struct {
int my_msg_type;
char msg_text[MAX_TEXT];
} my_msg_st;
int main () {
int running = 1;
my_msg_st some_data;
int msgid;
char buffer[MAX_TEXT];
if ((msgid = msgget((key_t)12345, 0666) | IPC_CREAT) == -1) {
perror("msgget!");
exit(EXIT_FAILURE);
}
while (running) {
printf("Enter the msg to send:");
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.msg_text, buffer);
if ((msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0)) == -1)
{
perror("msg_snd!");
exit(EXIT_FAILURE);
}
if (!strncmp(buffer, "end", 3)) {
running = 0;
}
}
return 0;
}
//= msg_receiver.c =================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
typedef struct{
int my_msg_type;
char msg_text[MAX_TEXT];
} my_msg_st;
int main (void) {
int running = 1;
my_msg_st some_data;
int msgid;
int msg_to_receive = 0;
if ((msgid = msgget((key_t)12345, 0666) | IPC_CREAT) == -1) {
perror("msgget!");
exit(EXIT_FAILURE);
}
while (running) {
if ((msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0)) == -1)
{
perror("msg_rcv!");
exit(EXIT_FAILURE);
}
printf("recieve msg : %s", some_data.msg_text);
if (!strncmp(some_data.msg_text, "end", 3)) {
running = 0;
}
}
if (msgctl(msgid, IPC_RMID, 0) == -1) {
perror("msgctl!");
exit(EXIT_FAILURE);
}
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.60.107.233
※ 編輯: xatier 來自: 210.60.107.233 (09/21 18:32)
→
09/21 18:44, , 1F
09/21 18:44, 1F
→
09/21 18:45, , 2F
09/21 18:45, 2F