EzDevInfo.com

c#-4.0 interview questions

Top c#-4.0 frequently asked interview questions

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)

Advertisements

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)

Pass to Value in C math

I am just learning C. i am working through this problem trying to predict the output:

#include <stdio.h>

int gNumber;
int MultiplyIt( int myVar );

int main (int argc, const char * argv[])
{
    int i; gNumber = 2;
    for ( i = 1; i <= 2; i++ )
        gNumber *= MultiplyIt( gNumber );
    printf( "Final value is %d.\n", gNumber );
    return 0;
}

int MultiplyIt( int myVar )
{
    return( myVar * gNumber );
}

so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512...

maybe i am missing something easy here, but as i said, i am very new to C and programing in general..


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)

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)

Rapidjson seg fault with g++ optimization

I am using Rapidjson and have noticed that when I turn on optimization in g++ (-O1/-O2/-O3) I am getting a segmentation fault. I think I have tracked it down to the GenericValue& AddMember() function within rapidjson.

GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
    RAPIDJSON_ASSERT(IsObject());
    RAPIDJSON_ASSERT(name.IsString());

    Object& o = data_.o;
    if (o.size >= o.capacity) {
        if (o.capacity == 0) {
            o.capacity = kDefaultObjectCapacity;
            o.members = reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member)));
        }
        else {
            SizeType oldCapacity = o.capacity;
            o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5
            o.members = reinterpret_cast<Member*>(allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member)));
        }
    }
    o.members[o.size].name.RawAssign(name);
    o.members[o.size].value.RawAssign(value);
    o.size++;
    return *this;
}

When debugging, I can see that kDefaultObjectCapacity ( is being optimized out (this is a static const SizeType kDefaultObjectCapacity = 16)

Therefore the line "o.capacity = kDefaultObjectCapacity;" is not being executed, and the malloc is mallocing 0 bytes then trying to cast it.

Why is this static const being removed?

I have tried making Object& o both volatile and static, neither worked. Any ideas?

Thanks Will

EDIT: I can't easily run the tests as it's on an embedded platform, rapidjson is built using buildroot at the moment. I tried the unit tests but couldn't get them going on the target.

I can have a look at providing the assembly, but it's part of a big application so it might be difficult finding the right bit.

For info, this is the method that calls the rapidjson code and this is where the problem seems to be:

int16_t FrontEndJSONHandlers::get_run_cfg_packer(JSONEngine& json_engine, char *message, int32_t *length)
{
Document doc;

// Need to pack an empty request to get the data
doc.SetObject();
doc.AddMember(JSONRPC_MEMBER, JSONRPC_VERSION, doc.GetAllocator());
doc.AddMember(METHOD_MEMBER, JSON_RPC_METH_GET_RUN_CFG, doc.GetAllocator());
doc.AddMember(ID_MEMBER, json_engine.GetNextMessageID(), doc.GetAllocator());

// Format the message
json_engine.FormatMessageAndRegisterResponseHandler(&doc, &message, &length, get_run_cfg_handler);

return 0;
}

If I make Document doc static, it doesn't seg fault - not sure whether this is the best way around it though?


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)

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)

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)

How would I scan over a string with someone's name and create initials for it?

So basically I need to get an input from a user (user's name) and then iterate over the user's name and create a new string of the initials. Then I have to output the initials. I'm pretty confused on how to do this in C.

One thing to keep in mind is that I have to use pointers. I can't use array operations as stated in my homework instructions. I think I'm on the right path, but I'm confused on how to concatenate characters to a string. Can someone help me out here?

Here is the code so far:

#include <stdio.h>
#include <string.h>

int main() {
    char *name = malloc(100);
    char c[5];
    char *initials = c;

    printf("Enter your full name in the following format 'First Middle Last':\n");
    fgets(name, 100, stdin);

    for(int i = 0; i < strlen(name); i++){
        if(name[i] == ' '){
            strcat(&name[i + 1], initials);
            printf("%s", initials);
        }
    }
}

Thank you!

Example input: Charles Edwin Roberts

Example output: C.E.R


Source: (StackOverflow)

How to randomize lowest bits in a 64 bit pattern

I am interested in learning more about the concepts behind bit shifting and the manipulation of randomly generated bits. Below is some code that prints 20 random 64 bit patterns. "rand_bits" uses the C standard rand() to return a 64 bit pattern with all zeros except for the lowest bits, which are randomized. The number of low randomized bits is provided by the only parameter to the function.

   const int LINE_CNT = 20;

    void print_bin(uint64_t num, unsigned int bit_cnt);

    uint64_t rand_bits(unsigned int bit_cnt);

    int main(int argc, char *argv[]) {

        int i;

        srand(time(NULL));
        for(i = 0; i < LINE_CNT; i++) {
            uint64_t val64 = rand_bits(64);
            print_bin(val64, 64);
        }
    return EXIT_SUCCESS;
    }


    void print_bin(uint64_t num, unsigned int bit_cnt) {

        int top_bit_cnt;

        if(bit_cnt <= 0) return;
        if(bit_cnt > 64) bit_cnt = 64;

        top_bit_cnt = 64;
        while(top_bit_cnt > bit_cnt) {
            top_bit_cnt--;
            printf(" ");
        }

        while(bit_cnt > 0) {
            bit_cnt--;
            printf("%d", (num & ((uint64_t)1 << bit_cnt)) != 0);
        }
        printf("\n");

        return;
    }


    /*
     * Name: rand_bits
     * Function: Returns a 64 bit pattern with all zeros except for the
     *           lowest requested bits, which are randomized.  
     * Parameter, "bit_cnt":  How many of the lowest bits, including the
     *           lowest order bit (bit 0) to be randomized
     * Return: A 64 bit pattern with the low bit_cnt bits randomized.
     */
    uint64_t rand_bits(unsigned int bit_cnt) {


        printf("int bit_cnt:", bit_cnt);
        uint64_t result = rand();
        uint64_t result_1 = result>>5;
// uint64_t result_1 = result>>7;

//return result;
        return result_1;

    }

For example, if the function is called with 24 as the argument value, it might return a 64 bit pattern, such as:

0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_​1101_0110_0101_1110_0111_1100

Currently the function rand_bits may show more than 15 random bits coming from the rand() function, but this is by NO means guaranteed.

I thought that to get the 40 bits like in the example I could right shift the bits, but that does not seem to be the concept. Does this require a bit mask of the higher order bits or a mod calculation on the random number generator?

Any suggestions of how to return a bit pattern of all zeros with its lowest bits (bit_cnt) randomized?


Source: (StackOverflow)