smallseo.info

c# interview questions

Top c# frequently asked interview questions

mongoLab C driver authentication and Basic Example

I am trying to interface Official C driver with mongoLab but getting error that failed to authenticate credentials. Do anyone have any simple example on how to interface mongolab using C driver. This is my example code

const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";

    uri = mongoc_uri_new(String_uri);
    client = mongoc_client_new_from_uri (uri);


   collection = mongoc_client_get_collection (client, "mydb", "mycoll");
   doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);

   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);

   if (count < 0) {
      fprintf (stderr, "%s\n", error.message);
   } else {
      printf ("%" PRId64 "\n", count);
   }

Source: (StackOverflow)

Connection refused on wpa_ctrl_open

I am trying to use C code to access wpa_supplicant in an ARM embedded system running linux. After searching, I realise that I could use wpa_supplicant control interface. I try to open a connection using wpa_ctrl_open(), and resulted in "Connection refused" error:

Failed to connect to wpa_supplicant global interface: /var/run/wpa_supplicant error: Connection refused

The code I am using to test:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
#include <netinet/if_ether.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "includes.h"

#ifdef CONFIG_CTRL_IFACE_UNIX
#include <dirent.h>
#endif /* CONFIG_CTRL_IFACE_UNIX */
#include "wpa_ctrl.h"
#include "common.h"

struct wpa_ctrl {
    int s;
#ifdef CONFIG_CTRL_IFACE_UDP
    struct sockaddr_in local;
    struct sockaddr_in dest;
#else // CONFIG_CTRL_IFACE_UDP
    struct sockaddr_un local;
    struct sockaddr_un dest;
#endif // CONFIG_CTRL_IFACE_UDP
};

static struct wpa_ctrl *ctrl_conn;

int main(int argc,char **argv)
{
    const char *global = "/var/run/wpa_supplicant";
    ctrl_conn = wpa_ctrl_open(global);
    if (ctrl_conn == NULL)
    {
        fprintf(stderr, "Failed to connect to wpa_supplicant "
            "global interface: %s error: %s\n",global,strerror(errno));
        return -1;
    }
    else
    {
        printf("Success\n");
    }
    return 0;
}

After tracing the code in wpa_ctrl.c, I found the problem is on the following IF condition, inside wpa_ctrl_open2() function:

if (connect(ctrl->s, (struct sockaddr *) &ctrl->dest,sizeof(ctrl->dest)) < 0)

I do not know what is the problem and how I can solve it.

On the same machine, I tried to run wpa_cli and it can access wpa_supplicant perfectly.

I used the following command to compile:

gcc -o test_wpa main.c wpa_ctrl.c os_unix.c -DCONFIG_BACKEND_FILE -DCONFIG_IEEE80211W -DCONFIG_DRIVER_WEXT -DCONFIG_WIRELESS_EXTENSION -DCONFIG_DRIVER_NL80211 -DCONFIG_LIBNL20 -DEAP_PSK -DIEEE8021X_EAPOL -DCONFIG_SHA256 -DCONFIG_CTRL_IFACE -DCONFIG_CTRL_IFACE_UNIX -DCONFIG_SME -lrt

wpa_supplicant code (including wpa_ctrl.c & os_unix.c) can be download at here: http://w1.fi/releases/wpa_supplicant-2.5.tar.gz

Many thanks in advance!


Source: (StackOverflow)

Count alphabets in C using log functions(without math.h) and arrays

I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:

    1                                           
    5   1 2 0 2 2 5 8     4 3 6 6 2   5 5 7 2 1 1   2   
    7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2 
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.

As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character. Now, this might seem silly, but what I have so far is this:

    #include <stdio.h>
    #include <ctype.h>

    /*
    int logBase10 (int num) {
       method to calculate the log base 10 of num
    }
    */

    int main (int argc, char * argv[]) {
        char alpha;
        int count = 0;
        int ascii[128] = {0};

        while ( (alpha = getchar()) != EOF) {
            count++;
            ascii[(int)alpha]++;
            alpha = getchar();
        }

        printf("Char \t Count \n");
        printf("------------------------\n");

        for (int i = 0; i < 127; i++) {
            if(ascii[i] > 0) {
                printf("%c \t %d \n", i, ascii[i]);
            }
        }
    }

Which produces an output like this:

    Char     Count 
    ------------------------

         5 
         93 
    ,    6 
    -    2 
    .    3 
    ;    2 
    C    2 
    I    6 
    N    1 
    T    1 
    W    2 
    a    26 
    b    5 
    c    8 
    d    13 
    e    55 
    f    11 
    g    7 
    h    28 
    i    32 
    k    3 
    l    26 
    m    17 
    n    31 
    o    27 
    p    12 
    q    1 
    r    26 
    s    22 
    t    42 
    u    11 
    v    8 
    w    8 
    y    13 
    z    1 

First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:

    if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
        printf("%c \t %d \n", i, ascii[i]);
    }

to no avail. Trying that produced more gibberish characters instead.

Any help/feedback is appreciated.

  • Soul

Source: (StackOverflow)

Having trouble using a C library via a Python API: What am I doing wrong?

I'm using a Python script in conjunction with a thermocouple and a thermocouple reader. To communicate with the thermocouple reader, which is written in C, I have to use an API. That API is PyDAQFlex. The thermocouple reader also came with a tester script, written in C. I'm trying to get a temperature reading from the thermocouple reader, but it only outputs the CJC value.

My code:

import daqflex

d = daqflex.USB_2001_TC()

def get_temperature():
    return float(d.send_message("?AI{0}:CJC/DEGC").encode("utf-8"))

The output of my code:

u'AI{0}:CJC/DEGC=23.8'

Note: 23.8 is not the temperature. That value is the CJC, as seen in the tester script's command line output below. It's related, but not the value I'm looking for.


The tester script's code:

http://pastebin.com/Atsdy7X0 (to get the temperature, I press "t" and then "k" because I have a K-type thermocouple).

The tester script's command line output:

http://pastebin.com/jq4Rr4QX (the temperature here is accurate. This is what I want to plug into my script.)


The PyDAQFlex script:

https://github.com/torfbolt/PyDAQFlex/blob/master/daqflex/devices.py (see line 105)

The C code for the thermocouple reader:

http://pastebin.com/rEDR9efR (Not included in entirety, only the relevant parts.)


I am seriously struggling to see my mistake here. This exact piece of code appears to have worked for someone else in the PyDAQFlex Github page, so I'm extremely confused. I have emailed the creator of the software, a person in Github with a similar issue as me, and I just spent 6 hours in various IRC chats. Please help me. If it helps, I used parts of this tutorial to install the drivers and things for the thermocouple reader. Thank you so much.


Source: (StackOverflow)

Read the entire contents of a file to c char *, including new lines

I'm looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I've got now:

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream
stream = fopen(argv[1], "r");

//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (should I add 1 for the \0?)
contents = (char *)malloc(fileSize);

//Read the file 
fscanf(stream, "%s", contents);     

//Print it again for debugging
printf("Read %s\n", contents);

Unfortunately this will only print the first line in the file so I assume that fscanf stops at the first newline character. However I would like to read the entire file including, and preserving, the new line characters. I'd prefer not to use a while loop and realloc to manually construct the entire string, I mean there has to be a simpler way?


Source: (StackOverflow)

Tree: Level order Traversal using queue

I wrote codes that traversing tree using queue, but dequeue function below generates error, Is there any problem with head = p->next ? I cannot figure out why this part is wrong.

void Levelorder(void) {
node *tmp, *p;


if (root == NULL) return;

tmp = root;
printf("The level order is :\n");

while (tmp != NULL) {

    printf("%d, ", tmp->data);
    if (tmp->left) {
        enqueue(tmp->left);
    }
    if (tmp->right) {
        enqueue(tmp->right);
    }
    tmp = dequeue();
}

return;
}

void enqueue(node *p) {
if (head == NULL) {
    head = p;
}
else {
    tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;

return;
}

node* dequeue(void) {
node *p;
p = head;
head = p->next;


if (head == NULL) {
    tail == NULL;
}

return p;
}

Source: (StackOverflow)

tm struct time.h not normalizing

I am adding values to the time (hours, minutes, seconds) members of my tm struct and they are not updating/normalizing even though I'm using mktime() Here is the code:

struct tm timeStruct;
char buffer[80];

timeStruct.tm_year = 2016 - 1900;
timeStruct.tm_mon = 3;
timeStruct.tm_mday = 32;
timeStruct.tm_hour = 23;
timeStruct.tm_min = 59;
timeStruct.tm_sec = 59;
timeStruct.tm_isdst = -1;

printf( "Date before adding interval: \n");
mktime(&timeStruct);
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

/*
 * Add intervals to time
 */
timeStruct.tm_sec += 2;
timeStruct.tm_min += 2;
timeStruct.tm_hour += 5;

printf( "Date after adding interval: \n");
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

Console Output:1

This is a print out of the console output:

Date before adding interval: 
Mon May  2 23:59:59 2016
the year is 116
the month is 4
the day is 2
the hours are 23
the minutes are 59
the seconds are 59
Date after adding interval: 
Mon May  2 28:61:61 2016
the year is 116
the month is 4
the day is 2
the hours are 28
the minutes are 61
the seconds are 61

I am using Eclipse, compiling with Cygwin, on a Windows 7 machine.


Source: (StackOverflow)

How to create a linear list for storing 10,20,30 using linked list?

How can I implement a linked list for storing 10,20,30 .Please help me with a simple example.


Source: (StackOverflow)

C Sockets Client/Server pthreads server broadcast

We were given this code, and was supposed to modify it so that whenever a client connects to a server and sends a message the server should reply I hear you dude. That is working for one and multiple clients but next task was to when ever a new client connects the server should tell that to all the other clients that are connected.

I assumed this would be fairly easy but its not working out like I thought it would. Since the server always get sock 3 and first client gets 4 and second client gets 5 etc, I tried to make a for loop that messaged whenever a new client connects the loop will send message to 4,5 which just made the server close itself directly. I then tried to just make when ever a new client connects that the server should message the first client(4) which it actually does but only if client(4) writes a message to the server he recieves that broadcast that the server sent.

So it seems like the client wants to write but needs to write something before he recieves the broadcast from the server, any help would appreciated since we're kinda beginners with all this.

This is how the code looks like at the moment.

server.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <pthread.h>

#define PORT 5555
#define MAXMSG 512


void *connection_handler(void *socket_desc)
{
    int sock = *(int*)socket_desc;
    int read_size;
    char *message, client_message[2000], *message_to_client;
    message = "Greetings! I am your connection handler\n";
    write(sock, message, strlen(message));
    while( (read_size = recv(sock, client_message, 2000, 0)) > 0)
    {
       client_message[read_size] = '\0';
       printf("Client[%d]: %s", sock, client_message);
       message_to_client = "I hear you dude...";
       write(sock, message_to_client, 19);
       memset(client_message, 0, 2000);
    }

    if(read_size == 0)
    {
       printf("Client[%d] disconnected", sock);
       fflush(stdout);
    }
    else if(read_size == -1)
    {
       perror("recv failed");

    }
    free(socket_desc);
    return 0;
}

int makeSocket(unsigned short int port) {
    int sock;
    struct sockaddr_in name;
    /* Create a socket. */
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock < 0) {
        perror("Could not create a socket\n");
        exit(EXIT_FAILURE);
    }
    name.sin_family = AF_INET;
    name.sin_port = htons(port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
        perror("Could not bind a name to the socket\n");
        exit(EXIT_FAILURE);
    }
    return(sock);
}

int main(int argc, char *argv[])
{
    int sock;
    int clientSocket;
    int i;
    int *new_sock;
    char *broadcast;
    fd_set activeFdSet, readFdSet;
    struct sockaddr_in clientName;
    socklen_t size;
    sock = makeSocket(PORT);
    if(listen(sock,1) < 0) 
    {
        perror("Could not listen for connections\n");
        exit(EXIT_FAILURE);
    }
    FD_ZERO(&activeFdSet);
    FD_SET(sock, &activeFdSet);
    while(1) 
    {
        printf("Waiting for connections\n");
        readFdSet = activeFdSet;
        if(select(FD_SETSIZE, &readFdSet, NULL, NULL, NULL) < 0)
        {
            perror("Select failed\n");
            exit(EXIT_FAILURE);
        }
        for(i = 0; i < FD_SETSIZE; ++i)
        {
            if(FD_ISSET(i, &readFdSet)) 
            {
                if(i == sock) 
                {
                    size = sizeof(struct sockaddr_in);
                    pthread_t sniffer_thread;
                    while(( clientSocket = accept(sock, (struct sockaddr *)&clientName, (socklen_t *)&size))) 
                    {
                        puts("Connection accepted");
                        new_sock = malloc(1);
                        *new_sock = clientSocket;
                        if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*) new_sock) < 0)
                        {
                            perror("could not create thread");
                            return 1;
                        }
                        broadcast = "NEW CLIENT CONNECTED";
                        write(4, broadcast, sizeof(broadcast)); //just to see if when ever a new client connects the first client should get all these messages
                        write(4, broadcast, sizeof(broadcast));
                        write(4, broadcast, sizeof(broadcast));
                        pthread_detach(sniffer_thread);
                        puts("Handler assigned");
                        FD_SET(*new_sock, &activeFdSet);

                   }
                   if(clientSocket < 0) 
                   {
                       perror("Could not accept connection\n");
                       exit(EXIT_FAILURE);
                   }                
                }
                else 
                {
                    if(readMessageFromClient(i) < 0)
                    {
                    close(i);
                        FD_CLR(i, &activeFdSet);
                    }
                }
            }
        }      
    }
} 

and for the client the code looks like this

client.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define PORT 5555
#define hostNameLength 50
#define messageLength  256

void initSocketAddress(struct sockaddr_in *name, char *hostName, unsigned short int port) 
{
  struct hostent *hostInfo; 
  name->sin_family = AF_INET;
  name->sin_port = htons(port);
  hostInfo = gethostbyname(hostName);
  if(hostInfo == NULL)
  {
    fprintf(stderr, "initSocketAddress - Unknown host %s\n",hostName);
    exit(EXIT_FAILURE);
  }
  name->sin_addr = *(struct in_addr *)hostInfo->h_addr;
}
void writeMessage(int fileDescriptor, char *message) 
{
  int nOfBytes;
  nOfBytes = write(fileDescriptor, message, strlen(message) + 1);
  if(nOfBytes < 0) 
  {
    perror("writeMessage - Could not write data\n");
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char *argv[]) 
{
  int sock;
  struct sockaddr_in serverName;
  char hostName[hostNameLength];
  char messageString[messageLength];
  char buffer[1024];
  if(argv[1] == NULL) 
  {
    perror("Usage: client [host name]\n");
    exit(EXIT_FAILURE);
  }
  else 
  {
    strncpy(hostName, argv[1], hostNameLength);
    hostName[hostNameLength - 1] = '\0';
  }

  sock = socket(PF_INET, SOCK_STREAM, 0);
  if(sock < 0) 
  {
    perror("Could not create a socket\n");
    exit(EXIT_FAILURE);
  }

  initSocketAddress(&serverName, hostName, PORT);
  if(connect(sock, (struct sockaddr *)&serverName, sizeof(serverName)) < 0) 
  {
    perror("Could not connect to server\n");
    exit(EXIT_FAILURE);
  }
  printf("\nType something and press [RETURN] to send it to the server.\n");
  printf("Type 'quit' to nuke this program.\n");
  fflush(stdin);
  recv(sock, buffer, 1024, 0);
  printf(buffer);
  while(1) 
  {
    printf("\n>");
      fgets(messageString, messageLength, stdin);
      messageString[messageLength - 1] = '\0';
      if(strncmp(messageString, "quit\n",messageLength) != 0)
         writeMessage(sock, messageString);
      if(recv(sock, buffer, 1024, 0) > 0)
               printf(buffer);


  }
}

Source: (StackOverflow)

Why does this simple program keep crashing visual studio 2013

This relatively simple program keeps on crashing my visual studio 2013, it doesn't give me an error message that i can tell you guys and from looking at my program I can't see any major flaws with it. Visual studio tries to debug it and than crashes. Can someone tell me what is wrong with my program?

#include <stdio.h>
int main()
{
    int a = 0, counter, total = 0;
    printf("enter the number of terms you want to display\n");
    scanf_s("%d", a);
    for (counter = 0; counter <= a; counter++){
        total = counter + total;
        printf("%d + ", total);
    }



    printf("You have finished the program, press enter to exit");       /*Letting the user know that the program is finished*/



}

Source: (StackOverflow)

How can I use getOpt to determine if no options are given in C?

I'm working on a simple program that supposed to change a string to all uppercase or all lowercase depending on the arguments. For example, if the programs name is change:

./change -u thiswillbeuppercase

THISWILLBEUPPERCASE

./change -l THISWILLBELOWERCASE

thiswillbelowercase

The issue im having if that i cannot figure out how to perform the uppercase action by default, if no options are provided. For example, this is how i would like it to perform:

./change thiswillbeuppercase

THISWILLBEUPPERCASE

Here is what my main function looks like currently:

int main(int argc, char *argv[]) {
int c;
while((c = getopt(argc,argv,"u:s:l:")) != -1){
    char *str = optarg;
    if(c == '?'){
        c = optopt;
        printf("Illegal option %c\n",c);
    } else{

        switch(c){
            case 'u':
                strupper(str);
                break;
            case 'l':
                strlower(str);
                break;
            case 's':
                strswitch(str);
                break;
            default:
                strupper(str);
                break;

        }
    }

}
return 0;

}

I tried calling the strupper function in the default part of the switch statement but that doesn't seem to work. As of now the program does nothing when provided with no options.

I search stackoverflow for similar questions and i found someone with the same issue, but their question is related to bash and not C.

If anyone has any advice i would really appreciate it. Thank you.


Source: (StackOverflow)

Rotate words around vowels in C

I am trying to write a program that reads the stdin stream looking for words (consecutive alphabetic characters) and for each word rotates it left to the first vowel (e.g. "friend" rotates to "iendfr") and writes this sequence out in place of the original word. All other characters are written to stdout unchanged.

So far, I have managed to reverse the letters, but have been unable to do much more. Any suggestions?

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_STK_SIZE 256

char stk[MAX_STK_SIZE];
int tos = 0; // next available place to put char

void push(int c) {
    if (tos >= MAX_STK_SIZE) return;
    stk[tos++] = c;
}

void putStk() {
    while (tos >= 0) {
        putchar(stk[--tos]);
    }
}

int main (int charc, char * argv[]) {
    int c;
    do {
        c = getchar();
        if (isalpha(c) && (c == 'a' || c == 'A' || c == 'e' || c ==         'E' || c == 'i' || c == 'o' || c == 'O' || c == 'u' || c == 'U')) {
            push(c);
        } else if (isalpha(c)) {
            push(c);
        } else {
            putStk();
            putchar(c);
        }
    } while (c != EOF);
}

-Soul


Source: (StackOverflow)

Redirecting file contents into another program in C

Making a basic shell and I need to handle file redirection. Specifically I am stumped on how I can feed data into a program like sort for example from a file.

Something on the command line would look like this:

$ sort < test.txt

How do I accomplish this kind of functionality in my own mini shell made in C?

I thought that maybe sort read from stdin but I guess I can't really write the contents of a file to stdin due to the read only aspect so I'm wondering how I actually get this data into something like sort for example? I am currently using forks and then using execvp() to execute programs.


Source: (StackOverflow)

Failed to build a naive project using Visual Studio 2015

I have failed to build a naive project using Visual Studio 2015.

It's a matter of environment which is still not fixed.

I am using Windows 10 Education, using Visual Studio Enterprise 2015.

Thank you so much for your help.

Error   TRK0005 Failed to locate: "CL.exe". The system cannot find the file specified.  myproj  D:\Documents\XXX    1   

Source: (StackOverflow)

Pass mach port to child process

I'm trying to pass a mach port to a child process created with fork on Mac OSX. I saw this SO question Sharing Mach ports with child processes but it doesn't have a solution it just describes the problem. Looking at this site https://robert.sesek.com/2014/1/changes_to_xnu_mach_ipc.html it contains directions on passing mach ports to a child process but their is no example code unfortunately.

I tried implementing the port swap but the child process can't receive the message that was sent by the parent process, mach_msg inside of recv_port fails with invalid name. Below is what I have so far. Sorry for so much code, mach IPC kind of makes it hard to be brief.

So how do I pass a mach port to a child process on Mac OSX now that the bootstrap port hack no longer works?

Edit

I changed the code example to reflect the points that Ken Thomases made in his answer, the child process creates a port with a send right and sends it to the parent. However the parent process can't receive the port created and sent by the child and just hangs on recv_port.

#include <stdio.h>
#include <mach/mach.h>
#include <mach/error.h>
#include <mach/message.h>
#include <unistd.h>

static int32_t
send_port(mach_port_t remote_port, mach_port_t port)
{
    kern_return_t err;

    struct
    {
        mach_msg_header_t          header;
        mach_msg_body_t            body;
        mach_msg_port_descriptor_t task_port;
    } msg;

    msg.header.msgh_remote_port = remote_port;
    msg.header.msgh_local_port = MACH_PORT_NULL;
    msg.header.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_COPY_SEND, 0) |
        MACH_MSGH_BITS_COMPLEX;
    msg.header.msgh_size = sizeof msg;

    msg.body.msgh_descriptor_count = 1;
    msg.task_port.name = port;
    msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
    msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;

    err = mach_msg_send(&msg.header);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't send mach msg\n", err);
        return (-1);
    }

    return (0);
}

static int32_t
recv_port(mach_port_t recv_port, mach_port_t *port)
{
    kern_return_t err;
    struct
    {
        mach_msg_header_t          header;
        mach_msg_body_t            body;
        mach_msg_port_descriptor_t task_port;
        mach_msg_trailer_t         trailer;
    } msg;

    err = mach_msg(&msg.header, MACH_RCV_MSG,
                    0, sizeof msg, recv_port,
                    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't recieve mach message\n", err);
        return (-1);
    }

    *port = msg.task_port.name;
    return 0;
}

static int32_t
setup_recv_port(mach_port_t *recv_port)
{
    kern_return_t       err;
    mach_port_t         port = MACH_PORT_NULL;
    err = mach_port_allocate(mach_task_self (),
                              MACH_PORT_RIGHT_RECEIVE, &port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't allocate mach port\n", err);
        return (-1);
    }

    err = mach_port_insert_right(mach_task_self (),
                                  port,
                                  port,
                                  MACH_MSG_TYPE_MAKE_SEND);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't insert port right\n", err);
        return (-1);
    }

    (*recv_port) = port;
    return (0);
}

pid_t
fork_pass_port(mach_port_t pass_port, int32_t (*child_start)(mach_port_t port, void *arg), void *arg)
{
    pid_t pid = 0;
    int32_t rtrn = 0;
    kern_return_t err;
    mach_port_t special_port = MACH_PORT_NULL;

    /* Setup the mach port. */
    if(setup_recv_port(&pass_port) != 0)
    {
        printf("Can't setup mach port\n");
        return (-1);
    }

    /* Grab our current task's(process's) HOST_NAME special port. */
    err = task_get_special_port(mach_task_self(), TASK_HOST_PORT, &special_port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't get special port:\n", err);
        return (-1);
    }

    /* Set the HOST_NAME special port as the parent recv port.  */
    err = task_set_special_port(mach_task_self(), TASK_HOST_PORT, pass_port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't set special port:\n", err);
        return (-1);
    }

    pid = fork();
    if(pid == 0)
    {
        mach_port_t host_port = MACH_PORT_NULL;
        mach_port_t port = MACH_PORT_NULL;

        /* In the child process grab the port passed by the parent. */
        err = task_get_special_port(mach_task_self(), TASK_HOST_PORT, &pass_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't get special port:\n", err);
            return (-1);
        }

        /* Create a port with a send right. */
        if(setup_recv_port(&port) != 0)
        {
            printf("Can't setup mach port\n");
            return (-1);
        }

        /* Send port to parent. */
        rtrn = send_port(pass_port, port);
        if(rtrn < 0)
        {
            printf("Can't send port\n");
            return (-1);
        }

        /* Now that were done passing the mach port, start the function passed by the caller. */
        child_start(pass_port, arg);

        /* Exit and clean up the child process. */
        _exit(0);
    }
    else if(pid > 0)
    {
        mach_port_t child_port = MACH_PORT_NULL;

        rtrn = recv_port(pass_port, &child_port);
        if(rtrn < 0)
        {
            printf("Can't recv port\n");
            return (-1);
        }

        /* Reset parents special port. */
        err = task_set_special_port(mach_task_self(), TASK_HOST_PORT, special_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't set special port:\n", err);
            return (-1);
        }

        return (0);
    }
    else
    {
        /* Error, so cleanup the mach port. */
        err = mach_port_deallocate(mach_task_self(), pass_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't deallocate mach port\n", err);
            return (-1);
        }

        perror("fork");

        return (-1);
    }
}

static int32_t start(mach_port_t port, void *arg)
{
    printf("Started\n");

    return (0);
}

int main(void)
{
    char *arg = "argument";
    mach_port_t port = MACH_PORT_NULL;

    pid_t pid = fork_pass_port(port, start, arg);
    if(pid < 0)
    {
        printf("Can't fork and pass msg port\n");
        return (-1);
    }

    return (0);
}

Source: (StackOverflow)