elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  CreateThread o CreateProcess
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: CreateThread o CreateProcess  (Leído 2,420 veces)
AlbertoBSD
Programador y
Moderador Global
***
Desconectado Desconectado

Mensajes: 3.696


🏴 Libertad!!!!!


Ver Perfil WWW
CreateThread o CreateProcess
« en: 21 Septiembre 2016, 17:07 pm »

Estoy haciendo un servidor en C el tema es cual funcion debo elegir como la deberia de aplicar.

Tengo 2 versiones de mi servidor, una para sistemas Unix y otra para Windows.

En unix no hay problema solo hago un fork y asunto resuelto:

Código
  1. if(listen(ListenSocket, BACKLOG) == -1) {
  2. perror("error: listen");
  3.  
  4.  
  5.        return 1;
  6.    }
  7. while(entrar) {
  8. pid = fork();
  9. switch(pid) {
  10. case 0:
  11. //Codigo para el Hijo
  12. break;
  13. case -1:
  14. //Error no fallo Fork
  15. break;
  16. default:
  17. //Get the PID for Parent
  18. break;
  19. }
  20. }

Pero no he encontrado una solucion para Windows, el servidor funciona bastante bien, el punto que en windows no es Multihilo aun, y tarda en responder ya que lo hace en orden secuencial.

He visto los siguientes enlaces y aun no doy con una solucion sencilla al tema

http://stackoverflow.com/questions/985281/what-is-the-closest-thing-windows-has-to-fork
http://stackoverflow.com/questions/14642496/any-simple-quick-way-to-fork-on-windows-ansi-c-beginthread-beginthreadex

Repito tengo 2 archivos distintos uno para Windows con winsock y el otro para Unix con Sockets estandar del sistema.

Saludos!


En línea

HardForo

Desconectado Desconectado

Mensajes: 219


HardForo.com


Ver Perfil WWW
Re: CreateThread o CreateProcess
« Respuesta #1 en: 21 Septiembre 2016, 17:41 pm »

La facil es compilar con Cygwin :) te va a funcionar fork() como esperas   ;-)



En línea

HardForo:  foro de Hardware y programación

Se buscan Mods y colaboradores *
AlbertoBSD
Programador y
Moderador Global
***
Desconectado Desconectado

Mensajes: 3.696


🏴 Libertad!!!!!


Ver Perfil WWW
Re: CreateThread o CreateProcess
« Respuesta #2 en: 21 Septiembre 2016, 17:48 pm »

Tengo Cygwin y funciona bien, el detalle que como voy a distribuir la aplicación, quiero que sea lo mas estándar posible (Acorde a cada sistema) y que dependa de la menor cantidad de recursos externos.

Saludos!

En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: CreateThread o CreateProcess
« Respuesta #3 en: 21 Septiembre 2016, 17:53 pm »

Yo lo haría con threads. De hecho, el de unix también lo haría con threads. Además, así no tendrías que hacer mucho cambio.
En línea

AlbertoBSD
Programador y
Moderador Global
***
Desconectado Desconectado

Mensajes: 3.696


🏴 Libertad!!!!!


Ver Perfil WWW
Re: CreateThread o CreateProcess
« Respuesta #4 en: 21 Septiembre 2016, 18:04 pm »

Si ya vi que lo que necesito es un thread nuevo lo cual seria lo mas parecido a fork aun que con ligeros cambios

Estoy validando este ejemplo de Windows:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682516(v=vs.85).aspx

Código
  1. #include <windows.h>
  2. #include <tchar.h>
  3. #include <strsafe.h>
  4.  
  5. #define MAX_THREADS 3
  6. #define BUF_SIZE 255
  7.  
  8. DWORD WINAPI MyThreadFunction( LPVOID lpParam );
  9. void ErrorHandler(LPTSTR lpszFunction);
  10.  
  11. // Sample custom data structure for threads to use.
  12. // This is passed by void pointer so it can be any data type
  13. // that can be passed using a single void pointer (LPVOID).
  14. typedef struct MyData {
  15.    int val1;
  16.    int val2;
  17. } MYDATA, *PMYDATA;
  18.  
  19.  
  20. int _tmain()
  21. {
  22.    PMYDATA pDataArray[MAX_THREADS];
  23.    DWORD   dwThreadIdArray[MAX_THREADS];
  24.    HANDLE  hThreadArray[MAX_THREADS];
  25.  
  26.    // Create MAX_THREADS worker threads.
  27.  
  28.    for( int i=0; i<MAX_THREADS; i++ )
  29.    {
  30.        // Allocate memory for thread data.
  31.  
  32.        pDataArray[i] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
  33.                sizeof(MYDATA));
  34.  
  35.        if( pDataArray[i] == NULL )
  36.        {
  37.           // If the array allocation fails, the system is out of memory
  38.           // so there is no point in trying to print an error message.
  39.           // Just terminate execution.
  40.            ExitProcess(2);
  41.        }
  42.  
  43.        // Generate unique data for each thread to work with.
  44.  
  45.        pDataArray[i]->val1 = i;
  46.        pDataArray[i]->val2 = i+100;
  47.  
  48.        // Create the thread to begin execution on its own.
  49.  
  50.        hThreadArray[i] = CreateThread(
  51.            NULL,                   // default security attributes
  52.            0,                      // use default stack size  
  53.            MyThreadFunction,       // thread function name
  54.            pDataArray[i],          // argument to thread function
  55.            0,                      // use default creation flags
  56.            &dwThreadIdArray[i]);   // returns the thread identifier
  57.  
  58.  
  59.        // Check the return value for success.
  60.        // If CreateThread fails, terminate execution.
  61.        // This will automatically clean up threads and memory.
  62.  
  63.        if (hThreadArray[i] == NULL)
  64.        {
  65.           ErrorHandler(TEXT("CreateThread"));
  66.           ExitProcess(3);
  67.        }
  68.    } // End of main thread creation loop.
  69.  
  70.    // Wait until all threads have terminated.
  71.  
  72.    WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
  73.  
  74.    // Close all thread handles and free memory allocations.
  75.  
  76.    for(int i=0; i<MAX_THREADS; i++)
  77.    {
  78.        CloseHandle(hThreadArray[i]);
  79.        if(pDataArray[i] != NULL)
  80.        {
  81.            HeapFree(GetProcessHeap(), 0, pDataArray[i]);
  82.            pDataArray[i] = NULL;    // Ensure address is not reused.
  83.        }
  84.    }
  85.  
  86.    return 0;
  87. }
  88.  
  89.  
  90. DWORD WINAPI MyThreadFunction( LPVOID lpParam )
  91. {
  92.    HANDLE hStdout;
  93.    PMYDATA pDataArray;
  94.  
  95.    TCHAR msgBuf[BUF_SIZE];
  96.    size_t cchStringSize;
  97.    DWORD dwChars;
  98.  
  99.    // Make sure there is a console to receive output results.
  100.  
  101.    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  102.    if( hStdout == INVALID_HANDLE_VALUE )
  103.        return 1;
  104.  
  105.    // Cast the parameter to the correct data type.
  106.    // The pointer is known to be valid because
  107.    // it was checked for NULL before the thread was created.
  108.  
  109.    pDataArray = (PMYDATA)lpParam;
  110.  
  111.    // Print the parameter values using thread-safe functions.
  112.  
  113.    StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"),
  114.        pDataArray->val1, pDataArray->val2);
  115.    StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
  116.    WriteConsole(hStdout, msgBuf, (DWORD)cchStringSize, &dwChars, NULL);
  117.  
  118.    return 0;
  119. }
  120.  
  121.  
  122.  
  123. void ErrorHandler(LPTSTR lpszFunction)
  124. {
  125.    // Retrieve the system error message for the last-error code.
  126.  
  127.    LPVOID lpMsgBuf;
  128.    LPVOID lpDisplayBuf;
  129.    DWORD dw = GetLastError();
  130.  
  131.    FormatMessage(
  132.        FORMAT_MESSAGE_ALLOCATE_BUFFER |
  133.        FORMAT_MESSAGE_FROM_SYSTEM |
  134.        FORMAT_MESSAGE_IGNORE_INSERTS,
  135.        NULL,
  136.        dw,
  137.        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  138.        (LPTSTR) &lpMsgBuf,
  139.        0, NULL );
  140.  
  141.    // Display the error message.
  142.  
  143.    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  144.        (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR));
  145.    StringCchPrintf((LPTSTR)lpDisplayBuf,
  146.        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
  147.        TEXT("%s failed with error %d: %s"),
  148.        lpszFunction, dw, lpMsgBuf);
  149.    MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK);
  150.  
  151.    // Free error-handling buffer allocations.
  152.  
  153.    LocalFree(lpMsgBuf);
  154.    LocalFree(lpDisplayBuf);
  155. }
  156.  

Aunque parece complicado veo que no esta dificil de implementar y ajustar a mi proyecto, lo que si tengo que hacer es una función nueva que seria el equivalente a lo que tengo dentro del switch incluso estoy dejando las 2 versiones con la misma cantidad de lineas y solo dejo huecos donde existe diferencia entre una version y la otra

Saludos!
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
api CreateProcess
Programación Visual Basic
cobra_90 1 1,360 Último mensaje 16 Septiembre 2006, 20:10 pm
por cobra_90
Hilos en vb6 sin CreateThread?
Programación Visual Basic
Zzombi 4 5,990 Último mensaje 2 Febrero 2010, 15:18 pm
por Zzombi
PROBLEMA CreateProcess() en QT
Programación C/C++
mikeltxus 1 2,385 Último mensaje 18 Noviembre 2011, 14:06 pm
por mikeltxus
Problema con CreateThread « 1 2 »
ASM
.:UND3R:. 10 6,455 Último mensaje 5 Septiembre 2012, 00:42 am
por .:UND3R:.
CreateThread para Servevidor en C
Programación C/C++
AlbertoBSD 2 1,938 Último mensaje 22 Septiembre 2016, 16:22 pm
por AlbertoBSD
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines