java-ProcessBuilder will not stop
I'm trying to decode an mp3 file to a wav file using the ProcessBuilder class under Linux. For some reason the process doesn't stop, so I have to cancel it manually.
Can someone give me a hint. I think the quoted code is easy to reproduce:
import java.io.*;public class Test { public static void main(String[] args) { try { Process lameProcess = new ProcessBuilder("lame","--decode","test.mp3","-").start(); InputStream is = lameProcess.getInputStream(); FileOutputStream fileOutput = new FileOutputStream("test.wav"); DataOutputStream dataOutput = new DataOutputStream(fileOutput); byte[] buf = new byte[32 * 1024]; int nRead = 0; int counter = 0; while((nRead = is.read(buf)) != -1) { dataOutput.write(buf, 0, buf.length); } is.close(); fileOutput.close(); } catch (Exception e) { e.printStackTrace(); } }}
output of jstack
"main"prio=10 tid=0x0000000002588800 nid=0x247a runnable [0x00007f17e2761000] java.lang.Thread.State: RUNNABLE at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:236) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read1(BufferedInputStream.java:275) at java.io.BufferedInputStream.read(BufferedInputStream.java:334) - locked(a java.io.BufferedInputStream) at java.io.FilterInputStream.read(FilterInputStream.java:107) at Test.main(Test.java:17)
Solution:
You need to empty the process's output (via getInputStream() ) and error (via getErrorStream() ) streams, otherwise it may block.
Quoting the Process documentation:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
(applies to error streams and output streams)
You may need to drain each stream in a different thread, as each stream may block when there is no data.
java-ProcessBuilder will not stop Related posts
- [timeisprecious][JavaScript ]JavaScript RegExp \W Metacharacter
JavaScript>RegExp regular expression> \W metacharacter1. From RunnobJavaScript RegExp \W metacharacterDefinition and usage:The \W metacharacter is used to find non-word characters.Word characters include: az, AZ, 0-9, and underscore.grammar:new RegExp("\W") or a simpler way: /\W/Demo:Case Code ...
- python-Use the string subs('x','w') instead of the symbol subs(x,w) to replace Sympy
I am working on an application with a circuit simulator ahkab, to make a long story short I need to replace the laplace variable s in some equations with 1j*w. For me, the symbol name is used instead of the symbol itself to perform this substitution and other substitutions. Convenience. I encountered some strange behavior.If you do>>> x = Symbol('x') >>> y = Symbol('y') >>> expr = x + y x + y >>> expr.subs('x','w') w + yThis seems to work as I expected. The pr ...
- php: output [] w / join vs $output.=
I am modifying some code, where the original author built a web page by using an array:$output[]=$stuff_from_database; $output[]='more stuff'; // etc echo join('',$output);Can anyone think of why this would be better (and vice versa):$output =$stuff_from_database; $output .='more stuff'; // etc echo ...
- w descriptors and sizes: Under the hood
Eric Portis digs into how the browser decides which image to downloads when you give it <img srcset=""sizes"">. Notably, a browser can do whatever it wants:Intentionally un-specified behavior lets browsers provide innovative answers to an open-ended question.Still, calculations happen based on ...
- In-depth analysis of the matching process of Python regular expressions \W+ and \W*
In the process of learning the re.split function, it was found that the execution and return of the following statements were inconsistent with what the old ape had expected:>>> re.split('\W*','Hello, world')['','H','e','l','l','o','','w', 'o','r','l','d','']What the old ape expects is ['', ...
- Python regular expressions \W* and \W*? Problems encountered in the matching process
When Lao Yuan analyzed the problem in"In-depth analysis of the matching process of Python regular expressions \W+ and \W*", he thought of a question, if"re.split('(\W*)','Hello, world') What will happen if the processing of"is changed to non-greedy mode? According to the prediction of the old monkey ...
- MongoDB Full Course w/ Node.js, Express, & Mongoose
Mongo DB (the"M"in MEAN and MERN stack) is among the most dominant databases in use today.Along with MySQL and PostgreSQL, Mongo DB an industry-standard database consideration among startups and large companies alike. But unlike the other two, Mongo DB is the de-facto standard for document based dat ...
- python-cannot get different records-Django w/ Rest Framework
I have this viewset defined, and I want to create a custom function that returns distinct animal species_types, called distinct_species.class AnimalViewSet(viewsets.ModelViewSet):"""This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions."""queryset = Animal. ...
- java - How does a JVM running multiple threads handle ctrl-c, w/ and w/o shutdown hooks?
Couldn't find this answer online. When pressing Ctrl C:What happens to the running threads when we don't have any shutdown hooks - they are each hit with InterruptedException? When we have shutdown hooks, I know that shutdown hooks run in new threads in arbitrary order. But what happens to existing ...
- javascript - ECMAScript associative array via object w/ prototype null?
I see a lot of people doing thisObject.prototype.foo = 'HALLO';var hash = {baz: 'quuz'};for ( var v in hash ) { // Do not print property `foo` if ( hash.hasOwnProperty(v) ) { console. log( v +"is a hash property"); }}My question is, instead of testing .hasOwnProperty every time you want to use Objec ...
- IronPython w/ C# - How to read the value of a Python variable
I have two python files: mainfile.py and subfile.pymainfile.py depends on some types in subfile.py.mainfile.py looks like this.from subfile import *my_variable = [1,2,3,4,5]def do_something_with_subfile #Do something with things in the subfile. #Return something.I'm trying to load mainfile.py in C# ...
- Python open(path,'w') cannot create file
I'm seeing strange behavior of Python open(..., 'w') on Linux. I create a bunch of files (file1...file100) in a new directory, each with:with open(nextfile, 'w') as f:It always fails if dir is empty:IOError: [Errno 2] No such file or directory: '../mydir/file1'There is no problem with permissions.If ...
- python – pip uninstall w / – environment flag?
I can't seem to get pip to uninstall packages when using environment flags.I created a virtual environment:virtualenv --no-site-packages /path/to/testenvWhile not in a virtual environment, I issue:pip install --environment /path/to/testenv djangoDjango is downloaded and installed.If I do the same co ...
- read the file name from the directory w/python
I am trying to make a pygame executable file. I will use the following installation file:from distutils.core import setup import py2exe setup( console = ["game.py"], author ="me", data_files = [(directory, [file_1, file_2...])] )I have made it work well in a simple game, but the game I want to package has> 700 image files. My question is, is there an easy way to read all file names from a directory, so I Don’t have to list each file name separately?Although some files are numbered sequentiall ...
- python file operation contact r+ w+ a+ understanding
Suddenly there was a sentence:"He has the ambition to master the four directions."The file operation trilogy: 1. Open with open first, 2. Write and close 3. Then go back to the middle writing operation. It is easy to close it as soon as it is opened, so write it first. . .The basic format f = open(" ...
- Python-invalid mode ('w') or file name
I encountered a very strange error.Many functions in my python script contain the following code:url=['http://agecommunity.com/query/query.aspx?name=', name,'&md=user']url=``.join(url)file = open("QueryESO.xml","w")filehandle = urllib.urlopen(url)for lines in filehandle.readlines(): file.write(l ...
Recent Posts
- python-Panda: the sum of two Boolean series
In Python:In [1]: True+True Out[1]: 2So after the following settings:import pandas as pd ser1 = pd.Series([True,True,False,False]) ser2 = pd.Series([True,False,True,False])What I want is to find the sum of the elements of ser1 and ser2, treating booleans as integers for addition, as shown in the Python example.But Pandas treats addition as an element-wise"or"operator and gives the following (unwanted) output:In [5]: ser1+ser2 */lib/python2.7/site-packages/pandas/computation/expressions.py:184: U...
- php - How to send email from localhost WAMP Server to email Gmail Hotmail etc?
See answer in English > (WAMP/XAMP) send Mail using SMTP localhost 6 I'm looking for correct information on how to send email from localhost WAMP. And how to authorize sending email from a specific authorized email address to send any other email address .How to configure this whole steps explain...
- Locale is not set programmatically in Android 5.0 Lollipop
My app sets the locale to Kitkat according to the selected language in the app. My code works fine. After updating to Lollipop, the locale is not set. Here, I paste my code to set the locale..Locale locale = new Locale("de_DE"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, null);Solution:You must change the way the locale is initialized. From here:Locale locale = new Locale("de_DE");Rega...
- The first machine learning algorithm: linear regression and gradient descent
The First Machine Learning Algorithm: Linear Regression and Gradient DescentSymbolic interpretation\(x^{(i)}\),\(y^{(i)}\): a training sample\(m\): total number of samples\(h_{\theta}\): Hypothetical functionLinear regressionHow to get a linear regression model?Put the training data into the learnin...
- python implements text segmentation
Text segmentation is an important step in data preprocessing for natural language understanding. This program implements the use of",.?!..."to segment articles, and to segment clauses into lines.import re pattern = r"([,.?!…])"#Regular matching pattern flags = [",",".","?","!","…"]sentence_txt = []w...
- junit gives error java.lang.NoClassDefFoundError: junit/framework/JUnit4TestAdapterCache
I am trying to do simple unit testing of my project at https://github.com/cdwijayarathna/oj4j.I added junit-4.12.jar and ant-junit4.jar to lib folder.But when I run"rake run_tests"I get the following error at the report location I gave.java.lang.NoClassDefFoundError: junit/framework/JUnit4TestAdapte...
- c#-TDD with MS test
Like all good programmers, when using TDD with MS Test, I am trying to be straightforward. I follow the basic arrangement, behavior, and assertion pattern, and the code for my behavior looks too complicated. I assume that the bill line There should only be one action. So, given that my sample code is as follows, do I perform an action first and then test its state? Thank you for your input.[TestMethod] public void TheCountOfAllRecordsIsGreaterThanZero() { //Arrange var auditLog = new AuditMaster...
- C# boolean logic with dynamic LINQ?
I have been working hard to accomplish the following tasks:Suppose I have a list containing names and values (e.g. Dictionary). I need to provide a field for the user of the web interface where he can write a query to check if a specific name and value exist on that list.For example, I have the following list:A = 2, B = 4, D = 0The user wants to query this list like this (don't mind the syntax, this is just a pseudo code)> A == 2&& D => This will return true because A exists and it...
- java - is there any chance to install a plugin that has not been released broken eclipse install
I use Eclipse Indigo for java development, but I want to try scala. Because I have to download the version that runs on Eclipse every night: http://scala-ide.org/download/nightly.html Is this safe?Is it possible for the plugin to break my eclipse installation because the plugin hasn't been fully rel...
- vue study notes day10 vue-resource and java back-end interaction
One vue interaction 1》jquery =>$ajax 2》js native: es6=>axios 3>》resource of vue get this.$http.get() this.$http.get("http://localhost:8080/MyBlogSys/test/run", { params: { act: 1, userName: "zhangsan" } }) .then(function(res) { console.log(res) }, function(err) { console.log(err) }); post this.$http.post() this.$http.post("http://localhost:8080/MyBlogSys/test/run", { act: 1, userName: "zhangsan" }, { emulateJSON: true } ) .then(function(res) { console.log(res) }, function(err) { con...