(let (dir "/foo")
(create-directory dir)
(with-current-directory dir
(delete-all-files-recursively)))
Factor recognized the value of dynamically scoped variables: http://concatenative.org/wiki/view/Factor/FAQ/What's%20Facto...A lot of code became much simpler because of that decision.
$ mkdir /tmp/foo && cd /tmp/foo && touch bar.txtThis style is pretty prevalent when writing test cases in shell (or just shell scripts in general), e.g. when using something like sharness[1].
http://www.gnu.org/software/bash/manual/bashref.html#index-s...
$ mkdir -m 0700Specifically, the code you wrote would behave the same if `dir` had lexical scope.
The scoping of the dir variable itself is irrelevant.
What the person meant when he wrote, "In those times I wish I could use the emacs lisp way," is, "In those times I wish I could use a lisp _macro_" -- particularly, one of those macros that makes a change, runs some code ("the body") then undoes the change.
Since all lisps have macros, the code above would work in any lisp -- not just Emacs Lisp. Among lisps, Emacs Lisp is famous for its dynamically scoped variables. Consequently, the specific reference to Emacs Lisp perpetuates the confusion that how variables are scoped has anything to do with what we have been talking about.
with-auto-compression-mode with-case-table
with-category-table with-coding-priority
with-current-buffer with-decoded-time-value
with-demoted-errors with-electric-help
with-help-window with-local-quit
with-no-warnings with-output-to-string
with-output-to-temp-buffer with-selected-frame
with-selected-window with-silent-modifications
with-syntax-table with-temp-buffer
with-temp-buffer-window with-temp-file
with-temp-message with-timeout
with-timeout-suspend with-timeout-unsuspend
with-wrapper-hookSo if fork is behaving as documented, returning -1 is because of "fork failing".
At what point do API authors share the blame for a needlessly harsh punishment delivered upon a predictably common error?
I certainly prefer to work with systems produced by people tending to think it'd be their fault more often than not.
It's just as wrong to feed kill() -1 as it would be to feed it -48585 or "babdkd" (unless that is explicitly your intention). A simple sanity check of if [ "${pid} > "0" ]; is all that's necessary to protect against this behavior.
So, I would argue, the fault lays on the users, not the creator, for not understanding the API when all materials necessary to understand said API are freely available.
(with that said, I think it's safe to say, we've all been bitten by not fully understanding some function before)
This kind of mistake is godawful and should not be defended. (but it's correctly fixed through stronger typing, not through choosing -48585 as the code for killing everything).
Actually, only -1 is the code that "kills everything"
> There'd be far fewer bugs if everyone knew exactly how everything else works.
Perhaps I misinterpreted your meaning, because you seem to be advocating using programming and scripting languages without actually bothering to learn them. Of course this can, will and does lead to very bad effects.
The bottom line is, if you are going to use a function in your program/script -- please, read the docs and understand what is will return at the very least.
You're arguing that people should read the API before doing anything with it. Parent's point is that this class of error can be avoided by strong typing (eg, via algebraic datatypes), negating the chance that it would happen in the first place. Which, I think, is the right way to look at the problem. But certainly, if you do have to use a weakly-typed, unsafe language which does not provide this kind of guarantee, be sure to read the documentation twice.
Which doesn't mean you won't get bitten when it turns out that the person writing a library you rely didn't RTFM.
Is there a reason fork can't be changed to just crash the program on failure? Are situations where a program usefully does something other than crash on fork failure, more or less common than situations where a program fails in the way described in the article?
If you were forking in a high-level language such as Python, failing to fork would raise an exception which would possibly crash the program if left unhandled.
C does not have exceptions so return codes are used to indicate success or failure. This is true for nearly every function, not just fork. If you're not checking for errors in a C program, it's going to break in unexpected ways, and will possibly be vulnerable to exploitation.
fork has 3 possible return values: - 0 for the child process - a positive number for the parent process - a negative number if it failed.
If you look at the man page's "Return Value" section, it is extremely clear, see: http://linux.die.net/man/2/fork
"On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately."
YES. Situation: fork bomb, can't create new processes. How do you notice? Typically because you can't spawn new processes from your shell because fork is failing. With bash, there is a kill builtin - so you have a chance of cleaning things up (depending) if you have a shell open. If the failed fork kills the shell, then oops, you don't have a shell open.
char *dir = "/foo";
mkdir(dir, 0700);
if (chdir(dir) == 0)
delete_all_files();with-temp-buffer is another example: a macro that bridges the functions for "string manipulation" and the ones for "buffer manipulation", since you start writing stuff this way:
(defun replace-in-string (str from to)
(with-temp-buffer
(insert str)
(beginning-of-file)
;;; Here you can use all your normal text editing commands
(replace-regexp from to nil t)
(buffer-string)))
Lots of dirty manipulation, but from outside its a pure function, and doesn't change the editor state in any way after it runs. char *olddir = getcwd();
chdir(newdir);
try {
do_stuff();
} finally {
chdir(olddir);
}Also, getcwd has a size parameter these days, and of course you want to check if the getcwd actually worked.
This is such a stupid problem I run into a lot. Both alternatives (doing things with absolute paths vs doing things entirely with relative paths) seem to have a lot of downsides. Overall relative paths seems to be way better, but then you leave yourself open to problems which "rhyme" with the one OP was talking about.
I was citing rearranging the tree is a potential issue with absolute directories, not with relying on CWD - that certainly could have been clearer.
"Also, you're assuming AT_FDCWD won't be -1, which could be reasonable but isn't guaranteed afaik."
Interesting point regarding guarantees. It's not -1 on any existing OS that I can find (it seems to be -100 on Linux and FreeBSD, -3041965 on Solaris, -2 on AIX), and shouldn't be for precisely this reason, but something to bear in mind if you are working on something more obscure that nonetheless has these functions.
Of course, you shouldn't be relying on reasonable behavior from functions passed a bad FD in general. It's just nice to have the additional defense when that does get missed.
It doesn't turn into a mess if you handle it correctly from the start. The way we ususally handle this in large applications is to have one single class like 'ApplicationPaths' which internally figures out all paths needed. No other code uses paths directly, instead always uses paths relative to ApplicationPaths.AppConfigDir/ApplicationPaths.UserConfigDir/ApplicationPaths.ExecutableDir and so on.
What is evil is a program changing its working directory. That's when it becomes an evil global variable, rather than a non-evil global constant.
I was wondering before if it would be interesting to have a filesystem with transactional locking of paths, though I'm sure the performance would take a hit. Would be kind of cool to be able to do filesystem operations without constantly opening yourself up to race conditions and requiring extremely defensive programming.
I agree that treating cwd as a global constant solves most (at least) of the issues, I'm just poking assumptions to see what ideas arise.
In a sense, this is "still a CWD" - but the differences would be 1) you can maintain multiple at the same time, and 2) you could close it.
Ever heard of PATH_MAX and ENAMETOOLONG? You will if you're using absolute paths everywhere. Sigh
To write that safely, you'd test for the result of mkdir and cd to return success before deleting.
In a shell, you'd just go
mkdir /foo -m 0700 && cd /foo && ${deleteallfiles}(Defensive Programming 101 really).
Also, don't rely on implicit state (the "current directory") for a destructive command, pass the dependency in:
recursively_delete_directory("/foo")
Reminds me of a time when I was working on a package system for an in-house linux os build and carelessly had my fakeroot directory set wrong in my configurations, which ended up treating my local root / directory as the root of the fakeroot, which is as bad as it sounds. Running the script over-wrote my entire /etc directory among other important and un-recoverable things...
Gladly, it was a development system so nothing crucial was lost. Needless to say, I am way more careful today in-part due to this mishap (and hours of setting up a new dev system!)
To avoid this, you have to either get a lock on that directory somehow (opening a transaction), or you have to try deleting the directory and then check the return code or catch any exceptions to tell whether the directory existed at the time of the attempted deletion.
This is why I found your "Defensive Programming 101 really" comment slightly arrogant (perhaps I misunderstood the intention). Writing correct programs is not easy and one should not mock others, because there is always something new to learn.
recursively_find_everything_in_current_directory() crashed due to a stack overflow when SetCurrentDirectory failed due to a single corrupt NTFS directory.
Running as non-root, the mkdir failed, the chdir failed, and it started eating my home directory.