Mini Porting guide of Linux Applications to Windows + NailGun (for faster startup of Java Apps) Windows Port Available + Review of NailGun Mini guía de Portar aplicaciones de Linux a Windows + NailGun (para el arranque más rápido de Java Apps) Windows Port Disponible + Examen de NailGun
Contents Sumario
- NailGun Introduction Introducción NailGun
- Rationale for Porting Razones para Portar
- Compiler choice: MinGW versus CygWin Compilador elección: MinGW versus Cygwin
- Mini Porting guide from Linux to Windows (networking focussed) Mini guía de Portar Linux a Windows (redes se centró)
- Testing Pruebas
- Code & Executable Download Código ejecutable y descarga
- Suggestions for improving NailGun Sugerencias para mejorar NailGun
NailGun Introduction Introducción NailGun
I was intrigued by the concept of Yo estaba intrigado por el concepto de nailgun which provides a way to run small Java apps significantly faster than the current procedure (load the jvm, run the app, upload the jvm). que proporciona una manera de ejecutar pequeñas aplicaciones Java significativamente más rápido que el procedimiento actual (carga de la JVM, corre la aplicación, cargar la JVM). The main issue with using the Sun JVM (java.exe) is the startup time of the JVM. El principal problema con el uso de la JVM de Sun (java.exe) es el tiempo de arranque de la JVM. For long running applications it is a non-issue, however for short running ones… Por mucho que las aplicaciones en ejecución no es un problema, sin embargo para correr más corto…
Note that Sun too has recently made some improvements by caching the jars of an application to reduce the startup time for bigger applications. Tenga en cuenta que Sun también ha hecho recientemente algunas mejoras de caché de los frascos de una solicitud para reducir el tiempo de inicio para las grandes aplicaciones. That still doesn’t address the startup time issue. Que aún no se aborda la cuestión el tiempo de arranque. So I think the solutions are complementary. Por tanto, creo que las soluciones son complementarias. It would be interesting if someone can do a benchmark on Windows. Sería interesante si alguien puede hacer una referencia a Windows.
The key concept of NailGun is that a Java server keeps running in the background and a small executable client ( written in C for speed ) is used to send the application details to the server for execution, details like application class name, command line arguments etc. El concepto clave de NailGun es que un servidor Java, sigue funcionando en segundo plano y un pequeño ejecutable cliente (escrito en C para la velocidad) se utiliza para enviar la solicitud de datos al servidor para su ejecución, detalles como la aplicación nombre de clase, argumentos de línea de comandos, etc .
As you can see from the above web page it can significantly speed up the startup time. Como se puede ver por encima de la página web se puede acelerar significativamente el tiempo de arranque. Also repeated running will conceivably further improve performance as the classes are already loaded in the JVM. También llevando a cabo en repetidas concebible seguir mejorando el rendimiento como las clases ya están cargadas en la JVM.
This is ideally suited for small command line applications like grep, wc, sort etc. , more so when you want to do some processing in a loop. Esto es ideal para pequeñas aplicaciones de línea de comandos como grep, wc, etc especie, más aún cuando usted quiere hacer alguna transformación en un bucle.
Rationale for porting & Why me? Razones para portar y ¿Por qué?
I think it can prove to be an useful tool in your toolbox specially for windows programmers as windows lack several useful command line utilities which can be trivially implemented (and has been implemented in many cases) in Java. Creo que puede resultar una herramienta útil en su caja de herramientas especialmente para los programadores como las ventanas carecen de ventanas de varios útiles utilidades de línea de comando que puede ser aplicado trivially (y se ha puesto en práctica en muchos casos) en Java.
I lead a massive porting effort 8 years back of porting over a million lines of C code (running on Solaris, AIX & Mac) to windows nt and windows 3.1. I liderar un masivo esfuerzo de portar 8 años de portar más de un millón de líneas de código C (corriendo en Solaris, AIX y Mac) para Windows NT y Windows 3,1. I had to deal with socket issues among a host of other. He tenido que hacer frente a cuestiones socket entre una multitud de otros. However it was on MSVC & Borland compilers. Sin embargo, fue en MSVC y compiladores de Borland.
So I thought yesterday to try my hand at porting some code on Así que pensé el día de ayer para intentar mi mano a portar algo de código en MinGW . My incentive was to re-hash the experience I had gained and hopefully learn some more. Mi incentivo fue re-hash la experiencia que ha adquirido y esperamos aprender algo más.
Why MinGW? MinGW ¿Por qué?
I avoided I evitarse Cygwin because of its dependence on cygwin dll and debido a su dependencia de las dll y cygwin licensing la concesión de licencias issues. cuestiones. Nailgun is on Apache license. Nailgun se encuentra en licencia Apache. Cygwin is on GPL. Cygwin es el GPL. This will force the executable to have more restrictive license than the original intention which is not desired. Esto obligará a los ejecutables tienen licencia más restrictiva que la intención original que no es deseado.
Mini Porting guide from Linux to Windows (networking focussed) Mini guía de Portar Linux a Windows (redes se centró)
Several networking related Linux headers files are not available in Windows. Varios de redes relacionadas con las cabeceras de archivos de Linux no están disponibles en Windows. Instead winsock.h or winsock2.h is a good replacement for them. En lugar winsock.h o winsock2.h es un buen reemplazo para ellos. You can use the following template: Puede utilizar la siguiente plantilla:
#ifdef WIN32 #include # ifdef WIN32 # include#else #include # # include otra persona #include # include #include # include #include # include #include # include #endif # endif
The file separator is different as you all know: El separador de archivo es diferente, como todos ustedes saben:
#ifdef WIN32 #define FILE_SEPARATOR '' #define MSG_WAITALL 0 #else #define FILE_SEPARATOR '/' #endif # ifdef WIN32 # define FILE_SEPARATOR''# define MSG_WAITALL 0 # # define más FILE_SEPARATOR '/' # endif Oh yes, MSG_WAITALL is not defined in Windows. Oh sí, MSG_WAITALL no está definido en Windows. The value 0 serves the purpose. El valor 0 sirve al propósito.
Windows implements Berkeley Socket in a half-hearted way. Windows Socket Berkeley lleva a cabo en un tibias. It requires invoking WSAStartup before making any socket calls. Se requiere invocar WSAStartup antes de hacer cualquier enchufe de llamadas. This is obviously not a requirement in Unix/Linux systems. Esto obviamente no es un requisito en Unix / Linux. A template code can be as follows: Un código de plantilla puede ser la siguiente:
#ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested = MAKEWORD( 2, 0 ); // 2.0 and above version of WinSock err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { fprintf(stderr, "Couldn't not find a usable WinSock DLL.n"); exit(NAILGUN_CONNECT_FAILED); // Replace with your own exit code } #endif # ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested = MAKEWORD (2, 0); / / 2,0 y por encima de la versión de WinSock err = WSAStartup (wVersionRequested, & wsaData); if (err! = 0) (fprintf (stderr, "No es posible no encontrar una utilizable WinSock DLL.n"); salida (NAILGUN_CONNECT_FAILED); / / Reemplazar con su propio código de salida) # endif Winsock version 2.0 and above is required for Winsock versión 2,0 y arriba es necesaria para select seleccionar functionality. funcionalidad.
And don’t forget to cleanup when done: Y no se olvide de la limpieza al terminar:
#ifdef WIN32 WSACleanup(); #endif # ifdef WIN32 WSACleanup (); # endif select seleccionar doesn’t work on files under windows. no funciona en los archivos bajo windows. This is a major difference from Unix/Linux systems where files are treated as sockets. Esta es una gran diferencia de Unix / Linux donde los archivos son tratados como sockets. Hence implemneting non-blocking calls on Windows becomes a hassle. Por lo tanto implemneting no bloquear las llamadas a Windows se convierte en una molestia. For I/O from console kbhit() can be used to find there was a key press (except certain control keys) and then getch() (no echo) or getche() can be used to fetch the characters. Para E / S de consola kbhit () puede ser usado para encontrar hubo de pulsar una tecla (con excepción de ciertas teclas de control) y, a continuación, getch () (sin eco) o getche () puede ser usado para obtener los caracteres. However the same technique doesn’t work when another program is using a pipe to send data to this program. Sin embargo, la misma técnica no funciona cuando otro programa está utilizando una tubería para enviar datos a este programa. Then overlapped I/O (Windows name for non-blocking I/O) can be used (ReadFile() or ReadFileEx()). A continuación, se superponen I / O (Windows nombre para no bloquear I / O) se puede utilizar (ReadFile () o ReadFileEx ()). ReadFileEx() is used for overlapped I/O only, whereas ReadFile() is used for both. ReadFileEx () se utiliza para superponen I / O sólo, mientras que ReadFile () se utiliza para ambos.
I found a ¡He encontrado un good article buen artículo which is better than Microsoft documentation on the subject. que es mejor que la documentación de Microsoft sobre el tema.
This is one part where the port is incomplete. Esta es una parte si el puerto está incompleto. It handles keyboard input well. , Que gestiona la entrada de teclado. However it doesn’t handle piped inputs. Sin embargo, no maneja hilo insumos. I leave it as a challenge for anyone who wants to gather experience on async file I/O in Windows platform. Dejo como un reto para cualquier persona que quiere adquirir experiencia en async archivo de E / S en plataforma Windows.
perror() doesn’t work for Socket calls. perror () no funciona para Socket llamadas. WSAGetLastError() must be used to get the error, if any, in the last socket call. WSAGetLastError () debe ser utilizada para obtener el error, en su caso, en los últimos zócalo de la palabra.
Note that for File I/O etc. GetLastError() returns the error code. Tenga en cuenta que para el archivo de E / S, etc GetLastError () devuelve el código de error.
For other details you can refer to Microsoft porting guide Para otros detalles, usted puede consultar a Microsoft para portar guía guide guía .
Interestingly the guide is silent on the above mentioned critical issues of porting. Es interesante que la guía no dice nada sobre las mencionadas cuestiones críticas de portar.
Final Notes: Notas finales:
1. Always remember to check and possibly handle the error codes. Siempre recuerda a comprobar y, posiblemente, el error de manejar códigos.
2. Remember to close the sockets before exiting No se olvide de cerrar la tomas antes de salir
Testing Pruebas
The code has been tested only on Windows 2000 Professional. El código ha sido probado sólo en Windows 2000 Professional.
However I think it should work well on Windows NT and XP versions. Sin embargo, creo que debería funcionar bien en Windows NT y XP versiones. About Windows 98 (Is it an Operating System or just a game playing console?) and Windows ME I am not too sure. Acerca de Windows 98 (¿Se trata de un sistema operativo o simplemente jugando un juego de consola?) Y Windows ME no estoy demasiado seguro.
Where do I get it? ¿Dónde puedo conseguirlo?
I have made available the He puesto a disposición el source code of the C port of ng.c (client) código fuente C del puerto de ng.c (cliente) and the resulting y la resultante executable ejecutable for invoking nailgun server. para hacer valer nailgun servidor. The rest should be downloaded from El resto debe ser descargado desde Source Forge Source Forge . The executable has been checked with AVG Virus Scanner with latest update installed. El ejecutable ha sido comprobada con AVG anti-virus con la última actualización instalada. However I insist that you too check it with your virus scanners. Sin embargo insisto en que usted también comprobar que su virus con escáneres.
Note: Nota:
The orginal code was developed by Martian Software. El código original fue desarrollado por Software de Marte. I just ported it to Windows. Acabo portado a Windows.
Disclaimer: Renuncia:
The code and executable software is supplied “as is”. El código ejecutable y software se suministra "tal cual". The publisher disclaims all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. El editor renuncia a toda garantía, expresa o implícita, incluyendo, sin limitación, las garantías de comerciabilidad o de idoneidad para cualquier propósito. The publisher assumes no liability for damages, direct or consequential, which may result from the use of the provided code or executable or any other software program downloaded from the Website. El editor no asume ninguna responsabilidad por daños y perjuicios, directos o indirectos, que pueden derivarse del uso de las previstas o código ejecutable o cualquier otro programa de software descargado desde el Sitio Web. The entire risk as to the quality and performance of the software is with you, and you assume the entire cost of any necessary servicing, repair or correction. El riesgo total con respecto a la calidad y el rendimiento del software es con usted, y usted asume todo el coste de cualquier servicio necesario, reparación o corrección.
Please check the Por favor, comprueba las instructions instrucciones .
Suggestions for improving NailGun Sugerencias para mejorar NailGun
1. Allow recognizing -cp (and other Java options) and load the classes dynamically Dejar de reconocer-cp (Java y otras opciones) y la carga de clases dinámicamente
2. Is it using a Thread Pool? ¿Está usando un hilo Piscina? If not it should be used Si no, debe utilizarse
3. Ability to reload classes Capacidad para recargar las clases
4. Ability to modify classes to disable System.exit and make the server more robust Posibilidad de modificar las clases para desactivar System.exit y hacer el servidor más robusto
5. Use a Java client and compile using MinGW on Windows Utilice un cliente Java y compilar utilizando MinGW sobre Windows
Filed under Filed under Java Software El software de Java , Linux , Windows | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article Enviar artículo
You may also like to read También puede leer |
The comments are currently closed for this post. Los comentarios están actualmente cerrados para este puesto.





November 23rd, 2004 at 10:29 pm 23 de noviembre de 2004 a las 10:29 pm
How many backslash does WordPress require? ¿Cuántos barra invertida hace WordPress requieren? I had to use 8 backslashes in the above post to get WordPress to generate two backslashes in the output (for specifying the file separator) ! Tuve que usar 8 barras en el post anterior para obtener WordPress para generar dos barras en la salida (para especificar el archivo separador)!
Wonder how many levels of processing the document endures before being published… Pregunto ¿Cuántos niveles de procesamiento perdura el documento antes de ser publicado…
And then I realized that if I edit the document, all the backslashes vanishes and only two remains! Y entonces me di cuenta de que si debo seguir para modificar el documento, todas las barras se desvanece y sigue siendo sólo dos!
November 24th, 2004 at 12:11 am 24 de noviembre de 2004 a las 12:11 am
Few Blog Entries of Note + Look at current ORM’s Pocas entradas del blog de Nota + Mira actual del ORM
Please see my posts on my other weblog : Por favor, vea mis entradas en mi otro weblog:
Another look at Internet Explorer (IE) security Otra mirada a Internet Explorer (IE) de seguridad
Several items like Linux to Windows Porting, Introduction, Review of NailGun, Download for Windows port of NailGun and misc. Varios temas como Linux a Windows Portar, Introducción, revisión de NailGun, descarga para Windows puerto de NailGun y misc. items artículos
Interesting arti Interesante artículo