vendredi 31 juillet 2015

Linux - Different threads of a process in different namespaces

I'm looking to open a netlink socket in each existing network namespace to listen for LINK messages associated with interfaces. I'd like to do this from a single process.

According to the 'setns()' documentation - "Given a file descriptor referring to a namespace, reassociate the calling thread with that namespace.". Can I therefore achieve my task by simply using 'pthread_create()' to create a thread for each namespace I require, call 'setns()' and then open the netlink socket.

The reason I ask is because I have seen conflicting information regarding 'setns()' acting on the process namespace.

How to receive a file from java to C via tcp/ip?

I have to send a file to java, and java has to receive the file and send it back to C via tcp/ip. I am able to send the file but in receiving i am not able to receive any data. I am giving the code for reference.

int send_text(int socket)
{
    FILE *text;
    char a[50];
    int size, read_size, stat, packet_index;
    char send_buffer[8008], read_buffer[8008];
    int wrt = 0, sock_fd, tsize = 0;
    packet_index = 1;
    int i = 0;
    text = fopen("/home/sosdt009/Desktop/character3.txt", "r");
    if (text == NULL)
    {
        printf("Error Opening text File:");
        exit(-1);
    }

    printf("Getting text Size:\n");
    gets(a);
    fseek(text, 0, SEEK_END);
    size = ftell(text);
    fseek(text, 0, SEEK_SET);
    printf("Total text size: %d \n", size);
    gets(a);

    //Send text Size
    printf("Sending text Size:\n");
    gets(a);
    send(socket, (void *) &size, sizeof(size), 0);
    while (size > tsize)
    {

        //Read from the file into our send buffer
        printf("Ready for sending:\n");
        gets(a);
        read_size = fread(send_buffer, 1, sizeof(send_buffer), text);
        printf("The size of send buffer:%c \n", sizeof(send_buffer));
        gets(a);
        printf("The read size value is :%d \n", read_size);
        gets(a);

        //Send data through our socket      
        for (i = 0; i < read_size; i++)
        {
            printf("Send value: %c \n", send_buffer[i]);
            gets(a);
        }

        do
        {
            stat = send(socket, send_buffer, read_size, 0);
            printf("The send size value is: %d \n", size);
            gets(a);
            printf("The read size value is: %d \n", read_size);
            gets(a);
        }
        while (stat < 0);

        printf("Packet %d, sent %d bytes.\n", packet_index, read_size);
        gets(a);

        //packet_index++;
        //Zero out our send buffer

        tsize = tsize + read_size;
        printf("The tsize value is:%d \n", tsize);
        gets(a);
        memset(send_buffer, 0, sizeof(send_buffer));

        if (read_size <= NULL)
        {
            printf("The connection is transferred to received text: \n");
            gets(a);
        }
    }

    fclose(text);
    printf("Text successfully send:\n");
    gets(a);

    return 0;
}

int receive_text(int socket)
{
    int buffersize, recv_size = 0, read_size = 1, write_size, size, stat;
    char *pBuf, a[50];
    int errno,i;
    FILE *text;
    text = fopen("/home/sosdt009/Desktop/receivednew.txt", "a");
    if (text == NULL)
    {
        printf("Error has occurred, text file could not be opened \n");
        return -1;
    }

    //Loop while we have not received the entire file yet
    while (read_size > 0)
    {
        ioctl(socket, FIONREAD, &buffersize);
        printf("The Buffersize is    :%d\n", buffersize);
        gets(a);
        printf("The size of socket is:%d\n", socket);
        gets(a);

        //We check to see if there is data to be read from the socket 
        if (buffersize > 0)
        {
            printf("Buffersize value is  :%d\n", buffersize);
            gets(a);
            pBuf = malloc(buffersize);
            if (!pBuf)
            {
                printf(errno, "Memory Error Cannot Allocate!\n");
                gets(a);
                exit(-1);
            }

            read_size = recv(socket, pBuf, buffersize, 0);
            printf("Read size value is :%d \n", read_size);
            gets(a);
            printf("Buffersize value is:%d \n", pBuf);
            gets(a);
            if (read_size < 0)
            {
                printf("%d\n", strerror(errno));
                printf("Data not written to the file:\n");
                gets(a);
                goto free;
            }

            //Write the currently read data into our text file
            write_size = fwrite(pBuf, 1, read_size, text);
            free(pBuf);
            printf("Write size value is   :%d \n", write_size);
            gets(a);
            printf("Buffer size value is  :%d \n", buffersize);
            gets(a);

            //Increment the total number of bytes read          
            recv_size += read_size;
            printf("Received size value is:%d \n", recv_size);
            gets(a);
            printf("Read size value is    :%d \n", read_size);
            gets(a);
        }
    }
    free: fclose(text);
    close(socket);
    printf("Text Successfully Received:\n");
    gets(a);

    return 0;
}

Adding the java code for further ref

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.net.ServerSocket;
  import java.net.Socket;
  public class Server1 {
  static ServerSocket serverSocket =null;
  private static Socket socket;
  public final static String FILE_TO_RECEIVED =   "/home/sosdt010/Desktop/Testfile/text2.txt";
  public final static int FILE_SIZE = 32092796 ;//4939993 ;//
  static int current=0;
  public static void main(String[] args) throws IOException,    InterruptedException {
  int port = 6777;
  serverSocket = new ServerSocket(port);
  System.out.println("Server Started and listening to the port 6777");
  socket = serverSocket.accept();
  InputStream is = socket.getInputStream();
  //ois=new ObjectInputStream(socket.getInputStream());
  //byte[] content = (byte[]) ois.readObject();
  FileOutputStream fos=new FileOutputStream(FILE_TO_RECEIVED );
  System.out.println(FILE_TO_RECEIVED);
  byte [] mybytearray  = new byte [FILE_SIZE];
  //  int bytesRead = is.read(mybytearray,0,mybytearray.length);
  // System.out.println(mybytearray.length);
  //current = bytesRead;
  //System.out.println(current+"/n"+bytesRead);
  int bytesRead;
   do {
         bytesRead =
         is.read(mybytearray, 0,mybytearray.length-current);

         if(bytesRead >= 0) current += bytesRead;
         System.out.println(bytesRead );

      } while(bytesRead > -1);
         for(int a=0;a<current;a++){
         fos.write(mybytearray[a]);
      }
          System.out.println(current +"new bytesread"+mybytearray.length);
      //fos.write(mybytearray, 0,current);
      System.out.println("Message received from server is "+current);


      OutputStream os=socket.getOutputStream();
      File myFile=new File(FILE_TO_RECEIVED);
      System.out.println(FILE_TO_RECEIVED);
      FileInputStream fis=new FileInputStream(myFile);
      byte[] mybytearray1=new byte[(int)myFile.length()];
      System.out.println(myFile.length());
      fis.read(mybytearray1, 0, mybytearray1.length);
      System.out.println("Bytes Read"+ mybytearray1.length);
      os.write(mybytearray1, 0, mybytearray1.length);
      System.out.println("Bytes write"+mybytearray1.length);
      System.out.println(mybytearray1.length);
      // byte[] content1 = Files.readAllBytes(new              File(FILE_TO_SEND).toPath());
      //oos.writeObject(content1);
       os.flush();

       fos.close();
       is.close();
       //fis.close();
       //os.close();
       socket.close();
    }
  }

I am giving the Receiving code that i am currently using in the program

    int receive_text(int socket)
{ 
    int buffersize[8192],recv_size = 0,read_size = 1, write_size, size; 
    char *pBuf,a[50]; 
    int errno;
    FILE *text; 
    text = fopen("/home/sosdt009/Desktop/receivednew.txt", "w");    
    if (text == NULL)   
    {       
        printf("Error has occurred, text file could not be opened \n");
        return -1;
    }

     //Loop while we have not received the entire file yet

      while (read_size > 0)
     {          
        ioctl(socket, FIONREAD, &buffersize);
        printf("The Buffersize is    :%d\n",buffersize);
        gets(a);
        printf("The size of socket is:%d\n",socket);
        gets(a);

        //We check to see if there is data to be read from the socket 

    if (buffersize > 0)
    {
        printf("Buffersize value is  :%d\n", buffersize);
        gets(a);
        pBuf = malloc(buffersize);
        /*if (!pBuf)
        {
            printf(errno, "Memory Error Cannot Allocate!\n");
            gets(a);
            exit(-1);
        }*/
             while ((read_size = recv(socket, buffersize, sizeof(buffersize), 0)) > 0)
        {
            fwrite(pBuf, 1, read_size, text); // plus error handling ...
        }

        //read_size = recv(socket, pBuf, buffersize, 0);
        //printf("Read size value is :%d \n",read_size);
        //gets(a);
        //printf("Buffersize value is:%d \n",pBuf);
        //gets(a);

        if (read_size < 0)
        {
            printf("%d\n",strerror(errno));
            printf("Data not written to the file:\n");
            gets(a);
            goto free;
        }

        //Write the currently read data into our text file

        write_size = fwrite(pBuf,read_size,1,text); 
        free(pBuf);
        printf("Write size value is   :%d \n",write_size);
        gets(a);
        printf("Buffer size value is  :%d \n",buffersize);
        gets(a);

        //Increment the total number of bytes read

        recv_size += read_size;
        printf("Received size value is:%d \n",recv_size);
        gets(a);
        printf("Read size value is    :%d \n",read_size);       
        gets(a);            
      }
    }
     free:
     fclose(text);
     close(socket);     
     printf("Text Successfully Received:\n");
     gets(a);
     return 0;
 }

Cannot compile and link AVR program in OS X

I am working on a mac with Yosemite OS X and I'm trying to compile a program in C that I could then upload onto my Arduino. I am following this tutorial specifically. I tried going through and reinstalling avr-gcc, but I got the same output. I tried searching for the file crtatmega328p.o on my system but it is nowhere to be found and the same goes for the directory. Any help would be appreciated.

$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o Program.o Program.c

$ avr-gcc -mmcu=atmega328p Program.o -o Program

/usr/local/lib/gcc/avr/5.2.0/../../../../avr/bin/ld: cannot find crtatmega328p.o: No such file or directory

/usr/local/lib/gcc/avr/5.2.0/../../../../avr/bin/ld: cannot find -latmega328p collect2: error: ld returned 1 exit status

Why we have used pointer in this C program?

Why we have used pointer in this C code? Basically, I am just searching a string in the array, but without pointer, it is unable to run. But why is that?

int main() {

    char *x[] = {"ab", "bc", "cd", 0};

    char *s = "ab";

    int i = 0;

    while(x[i]) {

            if(strcmp(x[i], s) == 0) {
                    printf("Gotcha!\n");
                    break;
            }

            i++;
    }
}

Why pointer is used in this code? [on hold]

I am a noob in C and studying the STRTOK function. I have found an example code where a pointer is used. but i don't know the reason why. Can anyone explain why?

int main()
{
    char str[80] = "I love you";
    const char s[2] = " ";
    char *token;
    token = strtok(str, s);

    while( token != NULL ) 
    {
        printf( " %s\n", token );
        token = strtok(NULL, s);
    }

    return(0);
}

I just read a text about this function. I found that, strtok function returns a pointer value itself. That's why we have used pointer here ( *token) I

Bug in implementation of python list resize?

In implementation of list (Python 3.4) I saw the following:

static int
list_resize(PyListObject *self, Py_ssize_t newsize)
{
    PyObject **items;
    size_t new_allocated;
    Py_ssize_t allocated = self->allocated;

    /* Bypass realloc() when a previous overallocation is large enough
       to accommodate the newsize.  If the newsize falls lower than half
       the allocated size, then proceed with the realloc() to shrink the list.
    */
    if (allocated >= newsize && newsize >= (allocated >> 1)) {
        assert(self->ob_item != NULL || newsize == 0);
        Py_SIZE(self) = newsize;
        return 0;
    }

    new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

    /* check for integer overflow */
    if (new_allocated > PY_SIZE_MAX - newsize) {
        PyErr_NoMemory();
        return -1;
    } else {
        new_allocated += newsize;
    }

    if (newsize == 0)
        new_allocated = 0;
    items = self->ob_item;
    if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
        PyMem_RESIZE(items, PyObject *, new_allocated);
    else
        items = NULL;
    if (items == NULL) {
        PyErr_NoMemory();
        return -1;
    }
    self->ob_item = items;
    Py_SIZE(self) = newsize;
    self->allocated = new_allocated;
    return 0;
}

and concretely line:

PyMem_RESIZE(items, PyObject *, new_allocated);

How I know, realloc may return another pointer, different from the obtained. I don`t understand how it works stable.

Seg Fault; Valgrind gives "Invalid Read of size 1"

I'm using the getopt function to parse out some command line arguments in the following format; ./a.out -b 16 -s 64 -n 2 < trace_file.trace. Currently, -b, -s work fine, but when I add the -n argument I get a seg fault. Through using Valgrind I get the following error information

==10472== Invalid read of size 1
==10472==    at 0x517A517: ____strtol_l_internal (strtol_l.c:298)
==10472==    by 0x5176F5F: atoi (atoi.c:27)
==10472==    by 0x4008EA: main (in /home/ian/a.out)
==10472==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==10472== 
==10472== 
==10472== Process terminating with default action of signal 11 (SIGSEGV)
==10472==  Access not within mapped region at address 0x0
==10472==    at 0x517A517: ____strtol_l_internal (strtol_l.c:298)
==10472==    by 0x5176F5F: atoi (atoi.c:27)
==10472==    by 0x4008EA: main (in /home/ian/a.out)

And here is my code snippet where I believe the error occurs. -b, -s, -n refer to block_size, set_sum, association_num respectively and parameter is of struct type cache which just simply holds the int values of block_size, set_sum, association_num.

while((c = getopt(argc, argv, ":s:b:n:")) != -1){
    switch(c){
        case 'b':
            parameter.block_size = atoi(optarg);
            b_size = parameter.block_size;
            break;
        case 's':
            parameter.set_num = atoi(optarg);
            num_sets = parameter.set_num;
            break;
        case 'n':
            parameter.associativity = atoi(optarg);
            association_num = parameter.associativity;
            break;
    }
}