Thread: Help Using Threads

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    39

    Post Help Using Threads

    Hey everyone,
    i'm very new to C programming, and i don't have enough knowledge of how to threads, i'm having the following program, i think i need to use threads in it, but i'm not really sure, what's ur opinion?
    this is a very simple http server, which loads up some html pages:
    here's the main function:
    Code:
    int main(int argc, char *argv[]) {
    
        int sock;
        int conn;
        pid_t  pid;
        struct sockaddr_in servaddr;
        
        /*  Create socket  */
    	sock = socket(AF_INET, SOCK_STREAM, 0);
    
        /*  Populate socket address structure  */
        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family      = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servaddr.sin_port        = htons(SERVER_PORT);
    
        /*  Assign socket address to socket  */ 
    	bind(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
    
        /*  Make socket a listening socket  */
    	listen(sock, LISTENQ);
    
        /*  Loop infinitely to accept and service connections  */
    
        while ( 1 ) {
    
    	/*  Wait for connection  */
    
    	if ( (conn = accept(sock, NULL, NULL)) < 0 )
    		perror("Error on accept");
    
    
    	/*  Fork child process to service connection  */
    
    	if ( (pid = fork()) == 0 ) {
    
    	    /*  This is now the forked child process, so
    		close listening socket and service request   */
    
    	    if ( close(sock) < 0 )
    		perror("Error on close in child");
    	    
    	    Service_Request(conn);
    
    	    /*  Close connected socket and exit  */
    
    	    if ( close(conn) < 0 )
    		perror("Error on close");
    	    exit(EXIT_SUCCESS);
    	}
    
    	/*  If we get here, we are still in the parent process,
    	    so close the connected socket, clean up child processes,
    	    and go back to accept a new connection.                   */
    
    	if ( close(conn) < 0 )
    		perror("Error on close in parent");
    	waitpid(-1, NULL, WNOHANG);
        }
    
        return EXIT_FAILURE;    /*  We shouldn't get here  */
    }
    and this is a simple bluetooth server, which has a send and receive function,
    Code:
    //rfcomm Server
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/socket.h>
    #include <bluetooth/bluetooth.h>
    #include <bluetooth/rfcomm.h>
    #include <stdlib.h>
    #include "server.h"
    
    char buffer[1024] = { 0 };
    
    
    
    int bt_recv()
    {
     while(1)
    {
        struct sockaddr_rc BASE_addr = { 0 }, CORE_addr = { 0 };
    
    	//variable deceleration
         int sock;
    	int conn;
    	int bytes_read;
    
        socklen_t opt = sizeof(CORE_addr);
    
        // Socket Allocation
        sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    
        // Socket Binding
        BASE_addr.rc_family = AF_BLUETOOTH;
        BASE_addr.rc_bdaddr = *BDADDR_ANY;
        BASE_addr.rc_channel = (uint8_t) 1;
        bind(sock, (struct sockaddr *)&BASE_addr, sizeof(BASE_addr));
    
        // Socket Listening
        listen(sock, 1);
    
        // Socket Accpeting
        conn = accept(sock, (struct sockaddr *)&CORE_addr, &opt);
    
        ba2str( &CORE_addr.rc_bdaddr, buffer );
        fprintf(stderr, "accepted connection from %s\n", buffer);
        memset(buffer, 0, sizeof(buffer));
    
        // read data after connection is established
        bytes_read = read(conn, buffer, sizeof(buffer));
        if( bytes_read > 0 ) {
            printf("Received Command: %s \n", buffer);
    	   printf("Command Logged!\n");
    	   logger();
        }
    
        // Socket Close
        close(conn);
        close(sock);
        return 0;
    }
    }
    //Logging Functions
    int logger()
    {
    	FILE *file;
    	file = fopen("file.txt","a+"); // apend file (add text to a file or create a file if it does not exist.
    	//writes the "buffer" to the txt file
    	fprintf(file,"# Command = %s\n", buffer );
    	fclose(file);
    	return 0;
    }
    //send function?
    int bt_send(const char *COMMAND)
    {
        struct sockaddr_rc addr = { 0 };
         int sock; //as in socket
    	int conn;
    	//since Core's MAC address is always fixed, its hard coded.
         char mac_address[18] = "00:03:7A:AA:92:DE"; //Core's MAC Address - Change if needed
    					         //00:1F:5C:E4:7F:34 E66
    						 //00:19:7E:F9:3B:92 Roy PC
    						 //00:03:7A:AA:92:DE Toshiba
    
        // Scoket Allocation
        sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    
        // set the connection parameters (who to connect to)
        addr.rc_family = AF_BLUETOOTH;
        addr.rc_channel = (uint8_t) 1;
        str2ba( mac_address, &addr.rc_bdaddr );
    
        // connect to Core
        conn = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
    
        // send message - Write a message on the socket (sock)
    	//payload should be applied here
        if( conn == 0 ) {
            conn = write(sock, COMMAND, 6);
        }
    	
    	//error handling
        if( conn < 0 ) perror("Error On Sending Message");
    	//Close Socket after sending 
        close(sock);
        return 0;
    }
    i need to have this bt_recv function running at the same time that i run the http server. i believe i need to use a thread for recv function, so both http and recv could process parallely. can anyone help me with this? an example code would be really nice

    thanks in advance

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    bt_recv() is not called inside your other server so the exact relationship between these two is not clear. Why do they have to run as part of the same program at all?

    Anyway, yes, you probably do need to thread that. A big factor in how would be the extent of the communication which must take place. Do you have a lot of variables you want to share? I think you could just use fork(), if you establish a means of communication between the servers using a socket.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    39

    Post

    Quote Originally Posted by MK27 View Post
    bt_recv() is not called inside your other server so the exact relationship between these two is not clear. Why do they have to run as part of the same program at all?
    i know, i can't call bt_recv() now, if i call it, the program crashes,
    i need to call bt_recv() somewhere in main function of http server, so the http server would host the pages, and bt_recv() would be waiting for incoming bluetooth messages synchronously.

  4. #4
    Registered User
    Join Date
    Jan 2009
    Posts
    39
    anyone?

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Ali.B View Post
    anyone?
    You still need to answer this question:

    A big factor in how would be the extent of the communication which must take place. Do you have a lot of variables you want to share [ie between the two processes]?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by rags_to_riches View Post
    I'd concur, that code is 100% taken from here:

    HTML output

    I'm guessing that the OP is not part of the other set of culprits, tho, due to his/her implied complete lack of knowledge. The OP may be a paying student of the other set of culprits (the "Rai Foundation") in which case this might all be interesting.

    Mr. Griffiths does appear to have a very nice site wherein he claims the programming section has tens of thousands of hits per month, so I guess this might all be predictable. I cannot see much significance to people "stealing" code of this sort* altho I am not Mr. Griffiths, in which case I might feel differently

    * of course, if I was a paying student of a group of people who have illegally stolen someone else's teaching material and claimed it as their own, I would be worried that I have given my money to a bunch of CHARLATANS who are unlikely to be able to provide me with an education, in which case I might need some help at cboard
    Last edited by MK27; 08-10-2009 at 02:07 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    Jan 2009
    Posts
    39

    Post

    Quote Originally Posted by MK27 View Post
    I'd concur, that code is 100% taken from here:

    HTML output

    I'm guessing that the OP is not part of the other set of culprits, tho, due to his/her implied complete lack of knowledge. The OP may be a paying student of the other set of culprits (the "Rai Foundation") in which case this might all be interesting.

    Mr. Griffiths does appear to have a very nice site wherein he claims the programming section has tens of thousands of hits per month, so I guess this might all be predictable. I cannot see much significance to people "stealing" code of this sort* altho I am not Mr. Griffiths, in which case I might feel differently

    * of course, if I was a paying student of a group of people who have illegally stolen someone else's teaching material and claimed it as their own, I would be worried that I have given my money to a bunch of CHARLATANS who are unlikely to be able to provide me with an education, in which case I might need some help at cboard
    lol.... i never said i coded the http server myself? i really would love someone to Quote that if i said it,first of all the school lets us to take codes from somewhere else and modify it if we need too,
    second: the purpose of this project that i'm doing, is NOT to learn how to code HTTP servers, but its all about learning SOCKET programming and BLUETOOTH programming ( in C with BlueZ) as i have in my bluetooth server (second part of code)... i wanted to add a GUI to my program and the best thing that came to my mind was to get a HTTP server from somewhere ( paul griffiths), modify it so i could use it with my own bluetooth server and then have and HTML hosted by this web server as a GUI....

    try to understand my case and then judge.

    i just needed to get some help from you, cuz i didn't know how to use pthreads.... why do i need pthread? cuz there's two processes at the same time processing parallely ; 1. web server 2. bt_recv() ... is this too hard to understand?

  9. #9
    Registered User
    Join Date
    Jan 2009
    Posts
    39

    Post

    Quote Originally Posted by rags_to_riches View Post
    get a life and try to grow up...

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Ali.B View Post
    try to understand my case and then judge.
    Alright, who cares.

    why do i need pthread? cuz there's two processes at the same time processing parallely ; 1. web server 2. bt_recv() ... is this too hard to understand?
    Why do you need pthreads? Three times now you have failed to answer a simple question:

    A big factor in how would be the extent of the communication which must take place. Do you have a lot of variables you want to share [ie between the two processes]?
    ... is this too hard to understand?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    Registered User
    Join Date
    Jan 2009
    Posts
    39
    A big factor in how would be the extent of the communication which must take place. Do you have a lot of variables you want to share [ie between the two processes]?
    no i don't have lots of variables to share, the only thing I need to do is to be able to receive bluetooth messages ( via bt_recv() ) at the same time of hosting web pages.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Ali.B View Post
    no i don't have lots of variables to share, the only thing I need to do is to be able to receive bluetooth messages ( via bt_recv() ) at the same time of hosting web pages.
    Conceptually, "I/you" who is able to receive these messages at the same time means:

    1) that "you" are someone operating a computer, or
    2) that "you" are a web server incorporating bluetooth messages into web page content, or
    3) that you want to control your http server using bluetooth

    Anyway, wow, that is a big project. But I would say only for #3 do you have to write a bluetooth server that is threaded into an http server, and even then perhaps not.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Jan 2009
    Posts
    39
    when i run the http server, it hosts some html pages; like index.html... in this html page, there's a button that sends messages using GET method in a FORM element.:
    <form action="send.htm" method="get">

    <input type="text" name="Text" value="START" />

    <input type="submit" value="Send Command" />

    </form>
    when this button is clicked , a string type data is sent to the web server, something like this:
    GET /send.htm?Text=START HTTP/1.1
    i managed to manipulate this string and parse the "START" part (which can differ according to the button clicked on web page) and act accordingly:
    in this way;
    if the parsed string is START then bt_send(START);
    if the parsed string is STOP then bt_send(STOP);

    bt_send() is on the bluetooth server part which sends bluetooth messages to other bluetooth device using MAC address- anyhow.. this is sorted out. no problem on this

    the receive part (bt_recv() ) also works when i run it alone - just a add a main method to it and it can recieve bluetooth messages... this is also sorted out

    think like this: when i run the bt_recv() alone, it's keep waiting for incoming messages, and every time that a message is received , it prints and then logs it.

    so what i've got now; is a web server that hosts some html pages, and messages can be SENT from the web page to bluetooth....
    what i want, is to have these two have these two processes at the same time, that means, at the same time that the web server is hosting web pages and is sending messages via those pages, it should also keep waiting for incoming bluetooth messages, just like the way that bt_recv() works alone....
    but since these two are two different processes, i need to use pthreads for each one... one for the web server and one for bt_recv()....
    my problem; i don't know how to use pthreads, do you?

  14. #14
    Registered User
    Join Date
    Mar 2003
    Location
    UK
    Posts
    170
    You will properly need to do something along the lines of the following skeleton code. Create the socket then pass the connection to a receiving thread to handle while the main thread listens on another socket for a new connection.
    Code:
    void bt_recv( void *conn )	  // Receiving thread
    {
    	...
    	int conn = (int) *conn;   // or * to structure with data etc...
    	do
    	{
    		rc = recv(conn, Buffer, sizeof(buffer), 0);
    		...	// do somthing with buffer here   
    	}while(rc != SOCKET_ERROR || rc > 0);
    	closesocket(conn);
    	// The thread will self destruct here.
    }
    
    int main(int argc, char* argv[])   // Main thread
    {
    	...
    	while ( 1 ) 
    	{
    		sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    		...
    		bind(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
    		listen(sock, 1);
    		conn = accept(sock, NULL, NULL);
    		_beginthread( bt_recv, 0, &conn );	 // Start receiving in new thread.
    		closesocket(sock);
    	}
    	...
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 10-17-2008, 11:28 AM
  2. Yet another n00b in pthreads ...
    By dimis in forum C++ Programming
    Replies: 14
    Last Post: 04-07-2008, 12:43 AM
  3. Classes and Threads
    By Halloko in forum Windows Programming
    Replies: 9
    Last Post: 10-23-2005, 05:27 AM
  4. problem with win32 threads
    By pdmarshall in forum C++ Programming
    Replies: 6
    Last Post: 07-29-2004, 02:39 PM
  5. Block and wake up certain threads
    By Spark in forum C Programming
    Replies: 9
    Last Post: 06-01-2002, 03:39 AM

Tags for this Thread