适应ç叉code到Java程序 [英] Adapting C fork code to a Java program

查看:92
本文介绍了适应ç叉code到Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建使用Java叉两个新的子进程的小程序。这是一个初学者的编程类谁的教程在C,所以我寻找一些帮助,了解一下这个code珍闻正在试图做的,什么是它适应基于Java的程序(以最好的方式最终建立就可以了)。

I am trying to create a small program using Java to fork two new child processes. It's for a beginner's programming class who's tutorials are in C, so I'm looking for some help to understand what this code tidbit is trying to do and what is the best way to adapt it to a Java-based program (to eventually build on it).

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
pid t pid;

    /*fork a child process*/
    pid = fork();

    if (pid < 0) { /*error occurred*/
        fprintf(stderr, "Fork Failed");
        return 1;
    }
    else if (pid == 0) {/*child process */
        execlp("/bin/ls", "ls", NULL); 
    }
    else { /*parent process*/
        /*parent will wait for the child to complete */
        wait(NULL);
        printf("Child Complete");
    }
    return 0;
}

更新:

我应该一个id附加到每个子进程,并与其父,打印信息子进程执行时和打印终止通知时终止。我现在看到上面code的该位列出当前目录下,并打印孩子完成的内容时,这个过程已经结束。是整个目录的上市考虑的一个过程?如果是这样,在哪里/如何在第二个新的子进程进入了吗?

I am supposed to attach an id to each child process and and its parent, printing the info when the child process executes and printing a termination notification when it terminates. I now see that this bit of code above lists the contents of the current directory and prints "Child Complete" when the process has terminated. Is the listing of the entire directory considered one process? If so, where/how does the second new child process come into the picture?

推荐答案

在Java中,这可能看起来像 -

In Java, that might look something like -

public static void main(String[] args) {
    try {
        Process p = Runtime.getRuntime().exec("/bin/ls");
        final InputStream is = p.getInputStream();
        Thread t = new Thread(new Runnable() {
            public void run() {
                InputStreamReader isr = new InputStreamReader(is);
                int ch;
                try {
                    while ((ch = isr.read()) != -1) {
                        System.out.print((char) ch);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        p.waitFor();
        t.join();
        System.out.println("Child Complete");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这篇关于适应ç叉code到Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆