Path: blob/master/test/jdk/java/lang/ProcessBuilder/FeelingLucky.java
41149 views
/*1* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* A test for25* 6469606: (process) Process.destroy() can kill wrong process (Unix)26* that is not suitable for use as a regression test, because it must27* create 32768 processes, and depends on perl.28*/29import java.io.*;3031public class FeelingLucky {3233public static void main(String[] args) throws Throwable {34final Runtime rt = Runtime.getRuntime();35final String[] pidPrinter = {"/bin/sh", "-c", "echo $$"};36final Process minedProcess = rt.exec(pidPrinter);37int minedPid = 0;38final InputStream is = minedProcess.getInputStream();39int c;40while ((c = is.read()) >= '0' && c <= '9')41minedPid = 10 * minedPid + (c - '0');42System.out.printf("minedPid=%d%n", minedPid);43minedProcess.waitFor();4445final String[] magnum = {46"perl", "-e",47"my $punk = getppid();" +48"open TTY, '> /dev/tty';" +49"print TTY \"punk=$punk\\n\";" +50"for (my $i = 0; $i < 32768; $i++) {" +51" my $pid = fork();" +52" if ($pid == 0) {" +53" if ($$ == " + minedPid + ") {" +54" print TTY \"MATCH $$ $punk\\n\";" +55" $SIG{TERM} = sub {" +56" print TTY \"Got TERM $$ $punk\\n\";" +57" kill 9, $punk;" +58" exit; };" +59" $| = 1; print 'Go ahead. Make my day.';" +60" sleep 100;" +61" }" +62" exit;" +63" } else { " +64" waitpid($pid,0);" +65" break if $pid == " + minedPid + ";" +66" }" +67"}"68};6970Process p = rt.exec(magnum);71if (p.getInputStream().read() != -1) {72System.out.println("got a char");73minedProcess.destroy();74Thread.sleep(1000);75}76}77}787980