manju sharma
manju sharma

Reputation: 35

Using write access in Open command in TCL

How can i use write ('w') and read ('r') access while using command pipeline in open command in TCL.

when i do something like :

set f1 [open "| ls -l" w]

it returns a file descriptor to write to , say file1.

Now I am confused how can I put this file descriptor to my use.

PS : My example might be wrong, and in that case it'd be ideal if answer includes a programming example so that it'll be more clear.

Thanks

Upvotes: 0

Views: 135

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137557

In general, the key things you can do with a channel are write to it (using puts), read from it (using gets and read), and close it. Obviously, you can only write to it if it is writable, and only read from it if it is readable.

When you write to a channel that is implemented as a pipeline, you send data to the program on the other end of the pipe; that's usually consuming it as its standard input. Not all programs do that; ls is one of the ones that completely ignores its standard input.

But the other thing you can do, as I said above, is close the channel. When you close a pipeline, Tcl waits for all the subprocesses to terminate (if they haven't already) and collects their standard error output, which becomes an error message from close if there is anything. (The errors are just like those you can get from calling exec; the underlying machinery is shared.)

There's no real point in running ls in a pure writable pipeline, at least not unless you redirect its output. Its whole purpose is to produce output (the sorted list of files, together with extra details with the -l option). If you want to get the output, you'll need a readable channel (readable from the perspective of Tcl): open "| ls -l" r. Then you'll be able to use gets $f1 to read a line from the subprocess.

But since ls is entirely non-interactive and almost always has a very quick running time (unless your directories are huge or you pass the options to enable recursion), you might as well just use exec. This does not apply to other programs. Not necessarily anyway; you need to understand what's going on.


If you want to experiment with pipelines, try using sort -u as the subprocess. That takes input and produces output, and exhibits all sorts of annoying behaviour along the way! Understanding how to work with it will teach you a lot about how program automation can be tricky despite it really being very simple.

Upvotes: 2

Related Questions