Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Combining C programs help

Options
  • 21-02-2008 2:06pm
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,086 Mod ✭✭✭✭


    Hello, I've written two programs that I want to combine. One is a server that is recieving a string of numbers(a serial number) from a client and the other is a program that starts up mysql and connects to a database when it is run.
    When I run this one program I want it to do both basically, the server sitting there recieving the strings that are sent to it and also starting up mysql. Then I can edit the program(hopefully) to update a mysql database with the strings.

    I would have thought this is a very simple thing to do but I just keep getting errors when i try it.

    I want to add this code:
    #include "stdafx.h"
    #include <windows.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //function prototype, basically just like a list of your functions
    
    PROCESS_INFORMATION StartMySQL(
    char *);
    
    int _tmain() {
    
    //"PROCESS_INFORMATION" is a structure used by CreateProcess.
    
    //We can refer to the process we create by using pi.hProcess
    
    //It's called a handle
    
    PROCESS_INFORMATION pi;
    
    pi = StartMySQL("-u root rfid ");
    
    //StartMySQL sets pi.hProcess=0 if there is an error
    
    if(pi.hProcess==0) {
    
    printf ("noooooooooo");
    
    return 0;
    
    }
    
    else {
    
    //Go to sleep for 5 seconds then kill the process
    
    //Sleep(5000);
    
    //TerminateProcess(pi.hProcess,0);
    
    }
    
    return 0;
    
    }
    
    PROCESS_INFORMATION StartMySQL(
    char *URL) {
    
    //If there is nothing in the [] it will calculate the length automatically
    
    //The \" is because DOS doesn't handle spaces well
    
    char PROGRAM_PATH[] = "\"C:/wamp/bin/mysql/mysql5.0.45/bin/mysql.exe\" ";
    
    PROCESS_INFORMATION pi;
    
    ZeroMemory( &pi, sizeof(pi) );
    
    STARTUPINFO si;
    
    ZeroMemory( &si, sizeof(si) );
    
    si.cb = sizeof(si);
    
    //Allocate enough memory for the parameters, the PROGRAM_PATH and the 00h at the end
    
    char *launchstring = (char *) malloc((strlen(URL)+strlen(PROGRAM_PATH)+1)*sizeof(char));
    
    if(!launchstring) { //launchstring=0 if it fails to allocate memory
    
    printf("malloc() failed");
    
    pi.hProcess=0;
    
    return pi;
    
    }
    
    //Copy PROGRAM_PATH and URL to launchstring
    
    strcpy(launchstring, PROGRAM_PATH);
    
    strcpy(launchstring+strlen(launchstring), URL);
    
    // Start the child process.
    
    if(!CreateProcess(NULL,launchstring,NULL, NULL, FALSE,0, NULL, NULL,&si,&pi))
    
    {
    
    printf("Createprocess Error: %d", GetLastError());
    
    pi.hProcess=0;
    
    return pi;
    
    }
    
    //Free the memory we allocated for launchsring with that malloc() line above.
    
    free(launchstring);
    
    return pi;
    
    }
    

    to this program:
    #define WIN32_LEAN_AND_MEAN
    #include <winsock2.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #pragma comment(lib,"ws2_32.lib")
    #define DEFAULT_PORT 2008
    //UDP by Default
    #define DEFAULT_PROTO SOCK_DGRAM
    
     
    
    void Usage(char *progname)
    {
        fprintf(stderr,"Usage: %s -p [protocol] -e [port_num] -i [ip_address]\n", progname);
        WSACleanup();
        exit(1);
    }
    
    int main(int argc, char **argv)
    {
        char Buffer[128];
        char *ip_address= NULL;
        unsigned short port=DEFAULT_PORT;
        int retval;
        int fromlen;
        int i;
        int socket_type = DEFAULT_PROTO;
        struct sockaddr_in local, from;
        WSADATA wsaData;
        SOCKET listen_socket, msgsock;
        /* Parse arguments, if there are arguments supplied */
    
        if (argc > 1)
           {
            for(i=1; i<argc; i++)
                  {
                         // switches or options...
                if ((argv[i][0] == '-') || (argv[i][0] == '/'))
                         {
                    // Change to lower...if any
                               switch(tolower(argv[i][1]))
                               {
                                      // if -p or /p
                        case 'p':
                            if (!stricmp(argv[i+1], "TCP"))
                                socket_type = SOCK_STREAM;
                            else if (!stricmp(argv[i+1], "UDP"))
                                socket_type = SOCK_DGRAM;
                            else
                                Usage(argv[0]);
                            i++;
                            break;
                                      // if -i or /i, for server it is not so useful...
                        case 'i':
                            ip_address = argv[++i];
                            break;
                                      // if -e or /e
                        case 'e':
                            port = atoi(argv[++i]);
                            break;
                        default:
                            Usage(argv[0]);
                            break;
                    }
                }
                else
                    Usage(argv[0]);
            }
        }
           // Request Winsock version 2.2
        if ((retval = WSAStartup(0x202, &wsaData)) != 0)
           {
            fprintf(stderr,"Server: WSAStartup() failed with error %d\n", retval);
            WSACleanup();
            return -1;
        }
        else
           printf("Server: WSAStartup() is OK.\n");
       
        if (port == 0)
           {
            Usage(argv[0]);
    		}
    
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);
        /* Port must be in Network Byte Order */
        local.sin_port = htons(port);
        // TCP socket
        listen_socket = socket(AF_INET, socket_type,0);
        if (listen_socket == INVALID_SOCKET){
            fprintf(stderr,"Server: socket() failed with error %d\n", WSAGetLastError());
            WSACleanup();
    
            return -1;
    
        }
    
        else
    
           printf("Server: socket() is OK.\n");
    
     
    
        // bind() associates a local address and port combination with the
        // socket just created. This is most useful when the application is a
        // server that has a well-known port that clients know about in advance.
    
        if (bind(listen_socket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
    
           {
    
            fprintf(stderr,"Server: bind() failed with error %d\n", WSAGetLastError());
    
            WSACleanup();
    
            return -1;
    
        }
    
        else
    
                  printf("Server: bind() is OK.\n");
    
     
    
           // So far, everything was applicable to TCP as well as UDP.
        // However, there are certain steps that do not work when the server is
        // using UDP. You cannot listen() on a UDP socket.
        if (socket_type != SOCK_DGRAM)
           {
            if (listen(listen_socket,5) == SOCKET_ERROR)
                  {
                fprintf(stderr,"Server: listen() failed with error %d\n", WSAGetLastError());
                WSACleanup();
                return -1;
            }
           else
                  printf("Server: listen() is OK.\n");
        }
        printf("Server: %s: Listening and waiting connection\non port %d, protocol %s\n", argv[0], port, (socket_type == SOCK_STREAM)?"TCP":"UDP");
       
           while(1)
           {
            fromlen =sizeof(from);
     
            // accept() doesn't make sense on UDP, since you do not listen()
            if (socket_type != SOCK_DGRAM)
                  {
                msgsock = accept(listen_socket, (struct sockaddr*)&from, &fromlen);
                if (msgsock == INVALID_SOCKET)
               {
                    fprintf(stderr,"Server: accept() error %d\n", WSAGetLastError());
                    WSACleanup();
                    return -1;
                }
               else
                  printf("Server: accept() is OK.\n");
                  printf("Server: accepted connection from %s, port %d\n", inet_ntoa(from.sin_addr), htons(from.sin_port)) ;
               
            }
            else
                msgsock = listen_socket;
     
            // In the case of SOCK_STREAM, the server can do recv() and
           // send() on the accepted socket and then close it.
           // However, for SOCK_DGRAM (UDP), the server will do
           // recvfrom() and sendto()  in a loop.
            if (socket_type != SOCK_DGRAM)
                retval = recv(msgsock, Buffer, sizeof(Buffer), 0);
           
           else
           {
                retval = recvfrom(msgsock,Buffer, sizeof(Buffer), 0, (struct sockaddr *)&from, &fromlen);
                printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr));
            }
               
            if (retval == SOCKET_ERROR)
                  {
                fprintf(stderr,"Server: recv() failed: error %d\n", WSAGetLastError());
                closesocket(msgsock);
                continue;
            }
           else
                printf("Server: recv() is OK.\n");
     
            if (retval == 0)
                  {
                printf("Server: Client closed connection.\n");
                closesocket(msgsock);
                continue;
            }
            printf("Server: Received %d bytes, data \"%s\" from client\n", retval, Buffer);
     
            printf("Server: Echoing the same data back to client...\n");
            if (socket_type != SOCK_DGRAM)
                retval = send(msgsock, Buffer, sizeof(Buffer), 0);
            else
                retval = sendto(msgsock, Buffer, sizeof(Buffer), 0, (struct sockaddr *)&from, fromlen);
           
                  if (retval == SOCKET_ERROR)
                  {
                         fprintf(stderr,"Server: send() failed: error %d\n", WSAGetLastError());
                   }
                  else
                         printf("Server: send() is OK.\n");
     
            if (socket_type != SOCK_DGRAM)
           {
                printf("Server: I'm waiting more connection, try running the client\n");
                printf("Server: program from the same computer or other computer...\n");
                closesocket(msgsock);
            }
            else
                printf("Server: UDP server looping back for more requests\n");
            continue;
        }
           return 0;
    }
    

    Is it just a matter of pasting in code in different places from one program to the other like I am trying?
    Thanks.


Comments

  • Registered Users Posts: 413 ✭✭ianhobo


    Well first off is this locally or remotely you want to do this?

    If locally, where is your mySql installed?
    What sort of errors are you getting?
    Did you comment out the thread related function calls? why?
    Is it just a matter of pasting in code in different places from one program to the other like I am trying?
    Yes and no
    I've written two programs that I want to combine

    I think this issue has come up before where you "wrote" some programs but don't know how they work.


  • Closed Accounts Posts: 413 ✭✭sobriquet


    I would have thought this is a very simple thing to do but I just keep getting errors when i try it.

    First things first, in your MySQL code, why is main called _tmain(), and where is that StartMySQL definition coming from? I've got the feeling you're running it from some kind of external stub which is the real starting point, would that be correct? (I've not written C/C++ in a while, so it might be normal but lost on me. Doesn't look like it though.)

    If so, you should still be able to make it work - take your current _tmain() code and put into its' own function in your server code. Rename the main() of that to _tmain() and whatever kind of harness you're using should run it. Call the MySQL code from there.

    Hard to say. Try that though, see what works.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,086 Mod ✭✭✭✭Tar.Aldarion


    ianhobo wrote: »
    Well first off is this locally or remotely you want to do this?
    Locally
    If locally, where is your mySql installed?
    What sort of errors are you getting?
    Did you comment out the thread related function calls? why?
    It doesn't matter about the mysql location(it says the location in the code if you want it) and the commented out function calls. I'm not sure by what you mean about the commented out bits, I have only commented out the terminate program process because I don't want the program to finish for now.
    The programs work fine, they both work seperately. I just don't know how to combine them into one program, the second program being in a function in the first etc.

    I think this issue has come up before where you "wrote" some programs but don't know how they work.
    I know how they work, they are edited programs really. I just have a problem combining them into one.
    First things first, in your MySQL code, why is main called _tmain(), and where is that StartMySQL definition coming from? I've got the feeling you're running it from some kind of external stub which is the real starting point, would that be correct? (I've not written C/C++ in a while, so it might be normal but lost on me. Doesn't look like it though.)
    I don't know much about _tmain, I have just began learning C/C++. When I start a project, tmain() is there by default.
    Here is what it says when I googled about it:
    http://www.codeguru.com/forum/showthread.php?threadid=358349
    It doesn't seem to make a difference I think...
    If so, you should still be able to make it work - take your current _tmain() code and put into its' own function in your server code. Rename the main() of that to _tmain() and whatever kind of harness you're using should run it. Call the MySQL code from there.

    Hard to say. Try that though, see what works.


    I'll try, thanks for the replies.


  • Registered Users Posts: 413 ✭✭ianhobo


    It doesn't matter about the mysql location

    Well it does, and yes I saw that. But this is quite clearly someone else code and you didn't say anything about any changes you made. So I have to ask.
    I don't if your understanding everythhins here. mySql is a process, and it has to be started. The path in the code is for a wamp installation. Have you got a wamp installation? You haven't given any info regarding your mySql installation, or any of the errors you say your getting
    I'm not sure by what you mean about the commented out bits,
    There are commented out bits of code. the lines start with this "//" the ones that are commented out, given their nature may have major implications in how this code runs, and how any copy and pasted interactions might happen

    as regards _tmain, it can matter, there is a difference. Just use main
    I know how they work, they are edited programs really. I just have a problem combining them into one.

    Can you post your attempt? and your errors, compiler, and mySql path


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,086 Mod ✭✭✭✭Tar.Aldarion


    ianhobo wrote: »
    Well it does, and yes I saw that. But this is quite clearly someone else code and you didn't say anything about any changes you made. So I have to ask.
    I don't if your understanding everythhins here. mySql is a process, and it has to be started. The path in the code is for a wamp installation. Have you got a wamp installation? You haven't given any info regarding your mySql installation, or any of the errors you say your getting
    Why does the location matter? Yes, I have a wamp installation. I believe I understand this code. I know it is a process and it has to be started, it is starting and running fine.
    I don't think you follow my problem, I have no problem with the codes I have posted, they both work exactly as I want them to and I think I understand them.
    The reason I have not mentioned MySQL is because I have no problems with it. The problem is just sticking programs together in one program.

    There are commented out bits of code. the lines start with this "//" the ones that are commented out, given their nature may have major implications in how this code runs, and how any copy and pasted interactions might happen
    I know they are commented out, I commented them out for testing, this is not a problem. I have no code problems, just amalgamating program problem.
    as regards _tmain, it can matter, there is a difference. Just use main
    Yeah, I'll just use main, I have been in my attempts.
    Can you post your attempt? and your errors, compiler, and mySql path
    I will get my attempt when I get to my laptop. The compiler is
    visual studio 2003 professional edition. The path to my mysql is C:/wamp/bin/mysql/mysql5.0.45/bin/mysql.exe
    Thanks.


  • Advertisement
  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,086 Mod ✭✭✭✭Tar.Aldarion


    Ok, I got it working, thanks for help!

    Time to try the next bit, updating mysql with the incoming strings.


  • Registered Users Posts: 413 ✭✭ianhobo


    I don't think you follow my problem

    Well I think I did. The reason that I had to ask you questions about your installation and what was going on was because despite the fact that you asked for help, you gave absolutely no information about the type of problem you were having. You provided no code attempts of your combination, no errors, no info about your system. Was I supposed to magically guess all of this?


  • Registered Users Posts: 6,494 ✭✭✭daymobrew


    sobriquet wrote: »
    First things first, in your MySQL code, why is main called _tmain(),
    Using _tmain() allows you to have common source for ANSI and UNICODE apps. Nothing wrong with that part of the code.
    From include\tchar.h:
    #ifdef UNICODE
    ....
    #define _tmain      wmain
    ...
    #else
    ...
    #define _tmain      main
    ...
    #endif
    


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,086 Mod ✭✭✭✭Tar.Aldarion


    ianhobo wrote: »
    Well I think I did. The reason that I had to ask you questions about your installation and what was going on was because despite the fact that you asked for help, you gave absolutely no information about the type of problem you were having. You provided no code attempts of your combination, no errors, no info about your system. Was I supposed to magically guess all of this?
    Sorry, should have been more specific, I wasn't really looking for you to fix the errors in my code so I didn't think my compiler etc were important, more how to combine two c programs in general. WAs it just paste in code to a new function and call taht function etc or did I have to do something else and so on.


Advertisement