Skip to content

Instantly share code, notes, and snippets.

@PersianDevelopers
Created September 22, 2019 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PersianDevelopers/e2b5855e1c992840fcd57604fc56dcd6 to your computer and use it in GitHub Desktop.
Save PersianDevelopers/e2b5855e1c992840fcd57604fc56dcd6 to your computer and use it in GitHub Desktop.
Sample Mach Message
//
// ViewController.m
// SampleMachMessage
//
// Created by Ali Pourhadi on 2019-09-21.
// Copyright © 2019 Ali Pourhadi. All rights reserved.
//
#import "ViewController.h"
typedef struct {
mach_msg_header_t header;
} mach_message;
@implementation ViewController {
mach_message sentMessage;
mach_message receivedMessage;
kern_return_t err;
mach_port_t port;
int messageId;
}
- (void)viewDidLoad {
[super viewDidLoad];
messageId = 0;
port = MACH_PORT_NULL;
err = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port); // Creating a port for comminucation
if (err != KERN_SUCCESS) {
printf("Failed to Allocate a port \n");
}
[self performSelectorInBackground:@selector(getMessage) withObject:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 repeats:true block:^(NSTimer * _Nonnull timer) {
[self sendMessage];
}];
}
- (void)sendMessage {
sentMessage.header.msgh_id = messageId++; /* MessageId */
sentMessage.header.msgh_remote_port = port; /*Destination Port*/
sentMessage.header.msgh_local_port = MACH_PORT_NULL;
sentMessage.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
sentMessage.header.msgh_size = sizeof(mach_message);
err = mach_msg (&sentMessage.header, /* The header */
MACH_SEND_MSG, /* Flags */
sizeof (sentMessage), /* Send size */
0, /* Max receive Size */
MACH_PORT_NULL, /* Receive port */
MACH_MSG_TIMEOUT_NONE, /* No timeout */
MACH_PORT_NULL); /* No notification */
}
-(void)getMessage {
int err;
receivedMessage.header.msgh_local_port = port;
receivedMessage.header.msgh_size = sizeof (mach_message);
while (true)
{
/* Receive a message. */
err = mach_msg (&receivedMessage.header, /* The header */
MACH_RCV_MSG, /* Flags */
0, sizeof (mach_message), /* Send/Max receive size */
port, /* Receive port */
MACH_MSG_TIMEOUT_NONE, /* No timeout */
MACH_PORT_NULL); /* No notification */
printf ("message: %i ", receivedMessage.header.msgh_id);
}
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment