-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path27.c
More file actions
81 lines (69 loc) · 2.13 KB
/
27.c
File metadata and controls
81 lines (69 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
============================================================================
Name : 27
Author : Piyush Singh
Description : Write a program to receive messages from the message queue.
a. with 0 as a flag
b. with IPC_NOWAIT as a flag
Date: 26th Sep, 2025.
============================================================================
*/
// Program: Receive messages from System V message queue (blocking and non-blocking)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
// Define message structure
struct msgbuf
{
long mtype;
char mtext[100];
};
int main()
{
key_t key;
int msgid;
struct msgbuf message;
// Step 1: Generate key
key = ftok("msgKeyFile", 'A');
if (key == -1)
{
perror("❌ ftok failed");
exit(1);
}
// Step 2: Access message queue
msgid = msgget(key, 0666);
if (msgid == -1)
{
perror("❌ msgget failed");
exit(1);
}
// Step 3a: Blocking receive (flag = 0)
printf("⏳ Waiting for message (blocking)...\n");
if (msgrcv(msgid, &message, sizeof(message.mtext), 0, 0) == -1)
perror("❌ msgrcv (blocking) failed");
else
printf("📥 Received (blocking): %s\n", message.mtext);
// Step 3b: Non-blocking receive (flag = IPC_NOWAIT)
printf("⚡ Trying non-blocking receive...\n");
if (msgrcv(msgid, &message, sizeof(message.mtext), 0, IPC_NOWAIT) == -1)
if (errno == ENOMSG)
printf("🚫 No message available (non-blocking).\n");
else
perror("❌ msgrcv (non-blocking) failed");
else
printf("📥 Received (non-blocking): %s\n", message.mtext);
return 0;
}
/*
Output:
╰─ ./26 ─╯
✅ Message sent to queue (ID: 65539): 📨 Hello from macOS sender!
╰─ ./27 ─╯
⏳ Waiting for message (blocking)...
📥 Received (blocking): 📨 Hello from macOS sender!
⚡ Trying non-blocking receive...
🚫 No message available (non-blocking).
*/