3

(Clojure newbie)

On my linux machine, slurping /proc/cpuinfo raises an error:

user=> (slurp "/proc/cpuinfo")
java.io.IOException: Invalid argument (NO_SOURCE_FILE:0)

Anybody knows why that is? (is the /proc filesystem some kind of second-class citizen in Java?)

Edit: the following code, adapted from nakkaya.com, works flawlessly:

(with-open [rdr (java.io.BufferedReader. 
             (java.io.FileReader. "/proc/cpuinfo"))]
   (let [seq (line-seq rdr)]
   (apply print seq)))

I wonder why this difference ?

Rom1
  • 3,167
  • 2
  • 22
  • 39
  • 1
    As far as java's concerned, /proc should be a directory like any other, with files and subdirectories. – Marc B Jan 19 '12 at 21:18

2 Answers2

6

I've had a similar problem with files in /proc. The solution is simple though:

(slurp (java.io.FileReader. "/proc/cpuinfo"))
MHOOO
  • 633
  • 6
  • 15
3

the problem is that java cannot open a DataInputStream on /proc so the slurp function isnt going to help you here, sorry :(

/proc/cpuinfo is a little strange because it has a file size of zero and produces bytes when read. this upsets the smarter java file handling classes.

ls -l /proc/cpuinfo
-r--r--r-- 1 root root 0 2012-01-20 00:10 /proc/cpuinfo

see this thread for more http://www.velocityreviews.com/forums/t131093-java-cannot-access-proc-filesystem-on-linux.html

you are going to have to open it with a FileReader. I'll add an example in a bit

Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • Also, why would `slurp` use a `DataInputStream` when it just needs to output a String and not parse it in any way ? – Rom1 Jan 19 '12 at 21:40
  • @Rom1, I'm not entirely sure what your question is here, but slurp does check the encoding. It's easy to look at the source and you will see it eventually calls InputStreamReader under the hood, which seems reasonable to me. See https://github.com/richhickey/clojure/blob/a1eff35124b923ef8539a35e7a292813ba54a0e0/src/clj/clojure/core.clj#L5353 – Adrian Mouat Jan 20 '12 at 12:46
  • @AdrianMouat, please don't link to the richhickey/clojure repo, it's waaay outdated. Use the clojure/clojure one instead. – Tim has moved to Codidact Jan 24 '12 at 14:10