简体   繁体   English

如何从Ubuntu中的Java程序运行C可执行文件

[英]How to run c executable file from a java program in ubuntu

I am unable to run c executable file from a java program in ubuntu. 我无法从ubuntu中的Java程序运行c可执行文件。

I created executable file using following command : 我使用以下命令创建了可执行文件:

gcc ex.c -o process

In java program i tried everything i could find but no result. 在Java程序中,我尝试了所有我能找到的,但没有结果。

Runtime.getRuntime().exec("/home/cori/Desktop/process.exe);

another method 另一种方法

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("process");

Please suggest. 请提出建议。

*nix like systems doesn't uses the *.exe postfix for executable files. * nix之类的系统不对可执行文件使用* .exe后缀。

Runtime.getRuntime().exec("/home/cori/Desktop/process") Runtime.getRuntime()。exec(“ / home / cori / Desktop / process”)

should work fine. 应该工作正常。 But I still don't get what result you want to get. 但是我仍然没有得到您想要得到的结果。 The only things you can get from a Process class is few streams, and its return status. 您只能从Process类中获得很少的流及其返回状态。 Which for you c program should be 0. (if you returned 0 end the end of your source code). 对您来说, c程序应为0。(如果返回0,则结束于源代码的结尾)。

And: The 2 methods you mentioned are the same. 并且:您提到的两种方法是相同的。 Just the first uses something call Method chaining :) 刚开始使用调用方法链接的方法:)

I am assuming you have access to the C code because I see you trying to compile it. 我假设您有权访问C代码,因为我看到您正在尝试对其进行编译。

Have you considered using Java Native Inteface? 您是否考虑过使用Java Native Inteface? Java allows you to call non-Java code, usually referred to as native code. Java允许您调用非Java代码,通常称为本机代码。

You have to follow a sequence of steps to get it work. 您必须遵循一系列步骤才能使其正常工作。 See an example here http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html 在此处查看示例http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

  1. Create a Java class with native method 使用本机方法创建Java类
  2. Load the library which implements the method 加载实现该方法的库
  3. Invoke the native method from Java 从Java调用本机方法
  4. Use javah utility to generate the header file 使用javah实用程序生成头文件
  5. Create c code to implement the java stub method 创建C代码以实现Java stub方法
  6. compile c program tp create .so or .dll (depending on OS) 编译c程序tp create .so或.dll(取决于OS)
  7. Set LD_LIBRARY_PATH 设置LD_LIBRARY_PATH
  8. Run the Java code 运行Java代码

It is a long process and It takes some trial and error to get it right. 这是一个漫长的过程,需要一些反复试验才能使其正确。 But once you figure it out it is a really powerful tool. 但是,一旦您弄清楚了,它就是一个非常强大的工具。 This is a very old feature of Java, so there are lots of resources online. 这是Java的非常老的功能,因此在线上有很多资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM