77 points · by objectivem · 7y ago · 104 comments
Edit: I really care about the "should" part too, not just what currently happens. I've been trying to think of semantics for forking that could work in these situations but I haven't been able to think of great solutions.
That solution is very obivious once you realize it is exactly the same as what happens with the terminal and network connections.
For example, after forking, both processes are still attached to the same terminal (what else can they do? It’s not like they can make new terminals - what if it was an ssh connection). They better agree who gets to read/write, or user will get confused - in shell, the parent voluntarily stops accesing terminal until the child is done.
or you simply avoid touching them. remember that forking only creates one new thread in the child process, there won't be any code running that you don't control or that would know about those file descriptors existing.
The reason fork (or vfork, or clone) and exec need to be separate steps is because you may want to do some stuff in between the two steps. The most obvious example is redirection: when you run "grep foo < bar", the shell needs to set stdin to point to "bar" before it execs "grep".
> The vfork() function shall be equivalent to fork(), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.
This roughly simplifies to "the only safe thing to do after a vfork is exec", and in this decade you can use posix_spawnp for that instead.
In particular, you can't do safely do anything that you'd normally want to after forking, like closing fds or moving them around (that'd be "calls any other function"). This means that unless the executable you're execing into is also under your control and knows what it's getting into, you have to mangle your fds &c. in the parent, vfork-and-exec, then undo the mess you've just made.
It is in principle _possible_ to navigate this error-prone process without observable side-effects. (The same could be said about implementing speculative execution, and look where we are now.) But I would hesitate to call it correct; the approach is clearly wrong, even if the result looks okay..
The situation is only slightly better if you're targetting some particular OS, which can provide stronger guarantees.
Note that these are different things: std::cin is a std::istream, std::cout and std::cerr are std::ostreams, and stdin, stdout, and stderr are FILE *s.
if (pid < 0) { /* TODO: handle error */ }
Reading the actual code I doubt it's just an oversight, the coding style used seems to lend strongly towards not thinking an error is possible: if ((pid = fork()) == 0)
{ //Child
longTask();
} else {
children[i] = pid;
}So does every tutorial which doesn't check the return from printf or check for errors from cout. Did you notice that the parent and child are both writing to the same file descriptor? Maybe the writer should add some words and tests in his code about the inherent race condition there. A true pedant would push this even further and teach their audience how to eliminate this problem with cross process mutexes or semaphores. Better be sure to check the error codes on those calls too.
I know arguing with a pedant is like wrestling with a pig, but honestly I'm more offended by the "#define N 2" than by the lack of error checking.
Please stop wasting electricity and time by writing shell scripts that fork processes to do ridiculously simple things like calling "bc" to add two numbers or "sed" to perform simple string manipulation, since your computer has a "mul" instruction that doesn't require millions of instructions and bytes of memory and disk accesses to perform.
It's like using Bitcoin to pay for a stick of gum.
https://www.quora.com/How-much-energy-does-it-take-to-make-a...
>According to Digiconmist, each bitcoin transaction took 215 kWh. Whereas an average Indian household consume : 90 kWh per month. It sums up that, each bitcoin consumption can power a average indian household for 2.5 months probably. The average electricity cost in India is 5 rupees per kwh.
It's like rolling coal because you want to trigger the libs.
https://www.youtube.com/watch?v=fkmLf5OXxz0
Stop and think before you write that shell script. It's not going to take you any more time to write it in Python, and then you won't be so shocked and surprised and totally fucked when you realize later that you need to add more features and make it more complicated than you originally though it would need to be in the first place.
It just boggles my mind that some people have such a hard time understanding how spectacularly inefficient shell scripts are, on top of how horrible to write, read, understand and maintain they are.
Sure, I love python, but if I want to find and filter some files nothing is easier to write than bash, so it's possible to have a quite big bash script even doing a good job and being well readable.
I'm honestly a little shocked that this doesn't seem to be common knowledge anymore and your post got upvoted so high.
My main language is Python btw.
Please don't tell me never to use spaces in file names.
How many human resources are required to track down and fix why a bash script suddenly starts failing mysteriously, years after it was written, when somebody mistakenly dares to use a space in a file name?
That kind of problem never happens with Python scripts (including problems with file names including other punctuation and unicode characters), because Python simply represents file names as strings.
For a scripting language that was indented to manipulate file names all the time, bash sure fucked up big time.
https://www.linuxjournal.com/article/10954
>Work the Shell - Dealing with Spaces in Filenames
>[...] I've outlined three possible solution paths herein: modifying the IFS value, ensuring that you always quote filenames where referenced, and rewriting filenames internally to replace spaces with unlikely character sequences, reversing it on your way out of the script.
>By the way, have you ever tried using the find|xargs pair with filenames that have spaces? It's sufficiently complicated that modern versions of these two commands have special arguments to denote that spaces might appear as part of the filenames: find -print and xargs -0 (and typically, they're not the same flags, but that's another story).
>During the years I've been writing this column, I've more than once tripped up on this particular problem and received e-mail messages from readers sharing how a sample script tosses up its bits when a file with a space in its name appears. They're right.
>My defensive reaction is “dude, don't use spaces in filenames”, but that's not really a good long-term solution, is it?
>What I'd like to do instead is open this up for discussion on the Linux Journal discussion boards: how do you solve this problem within your scripts? Or, do you just religiously avoid using spaces in your filenames?
>Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
(Dave wrote that 8 years ago, and there are still zero comments on it. Nobody has a good solution! Bash is just permanently fucked when it comes to file names.)
#!/bin/bash
# run this scri0t with 0 or more filename args
for file in "$@" ; do
do_something_with "${filename}"
done
> Nobody has a good solution! Bash is just permanently fucked when it comes to file nameFrom the man page bash(1):
Special Parameters
@ Expands to the positional parameters, starting from one.
When the expansion occurs within double quotes,
each parameter expands to a separate word.
That is, "$@" is equivalent to "$1" "$2" ...And good for them! What kind of savage puts spaces on their filenames?
In any case I don't say put in a Bash script and let it grow to ten million lines over 20 years.
My approach to bash scripts is this:
1. start with a bash script to understand a problem and see how a solution might be structured. PoC level is enough here.
2. When you know you solve the right problem and the customer is willing to make something bigger, then put ~80% of the code in a good programming language (Python is my personal favorite, but Ruby, Java, PHP, C#, C++, Lisp might also work). That happens about 3 months into a project.
3. If you start to hit bottlenecks and performance ceilings put the 30-50% that are relatively stable and most performance hungry into C/C++ code and really optimize the heck out of it. This should be done only with an aged project, like 2 years in, and very pessimistically, since highly optimal code usually is badly readable and badly maintainable. You certainly don't want to go into that code 6 years later and drastically change its API to your python code.
So a ten year project would have a thin layer of bash/docker at the top, a strong core of highly flexible code (of Python for me as well) in the middle, and a leg of high performance C code here and there.
I honestly have never seen a project that really needed the C-layer though. In modern IT world it seems most problems are old at least from a political/management point of view between 2 weeks and 3 months. So in fact, although I count myself as a Python coder, the last few years I've spent writing way more bash and docker related stuff, which then is either never touched again or directly thrown away after a few weeks, no matter if successful or not.
PS: Please don't use spaces in file names. Not just for scripts. It is also not clear for users where something ends, and they are even less used to putting string indicators around file names than you are about handling spaces with bash there.
And last but not least stuff like spaces in filenames, starting scripts with upper case letter etc, they might even be just a small annoyance. But you can be sure that skilled developers will put you 2 classes below their average when they see this, because it simply shows a lack of the right spirit.
For simpler, more expressive Python system scripts use Plumbum: https://plumbum.readthedocs.io/
> but if I want to find and filter some files nothing is easier to write than bash
That's like 10 lines in Python and much easier to read and test.
Look. We are working an professional field with a strong scientific foundation. There is no "this bridge is harder to drive over for me therefore I think it's bad architecture". The easiness and expressiveness depend on the problem you try to solve, not on the people, their tastes or their experience.
Shell tools are highly optimized to work in pipes, to work on files and to work on line separated entries like lines of code or lines of CSV. So if you have a problem where you need to pipe file handling into some filtering and into some line based transformations then you will have a hard time to find anything as easy or expressive as a bash script. And most projects on a unix-like operating system at least start like this: Understand the problem based on database dumps, logs, csv data measurements, previously written code etc.
If your regular expressions are not able to cover all the edge cases anymore and/or become unreadably complex then of course you should start an actual program. That only happens a few weeks into most topics though.
> doubly so when you need to throw more of them at this thing written by a former developer that thought he or she was saving money for the org by not spending an extra 30 minutes writing the program in Python or Go.
Yes, there are people who lack the skill or ambition to develop good code. We all hate when we need to deal with their stuff. But honestly, would they have written better code if they had used Python or Java or C++ for that problem? Unlikely.
A good coder would have some feeling for when he outsources some functionality to a python script. And if he develops a code base for a longer time most of his code will be in a real programming language. But even then it might be wrapped into a thin layer of bash to use find or grep or something that cleans up the input a little.
It's a single command in bash, invoking a program far more efficient than anything you can put together in python. It is literally a tool written for this exact purpose. I think it is simply ridiculous to not use a pre-existing tool that frankly you cannot out-do with a scripting language.
Even if you are writing a python script, you should _still_ use find to search for files if there is _any_ complexity in the search requirements.
Have you actually measured the amount of energy each takes? I would not be surprised if the Python VM's startup makes it more inefficient.
That is because Python actually has a built-in way to multiply numbers and perform string manipulation, right out of the box, without forking another process! The overhead of the Python interpreter required to get to that "mul" instruction is nothing compared to the overhead of forking another process to run "dc". This isn't rocket science, it's not even close. You really should check it out some time. So do a lot of other languages. Just not bash.
I can't believe I need to explain this. This isn't about Python being amazingly well designed or efficient. It's about bash being extremely badly designed and inefficient, and people having absolutely no clue how expensive it is to fork processes like "bc" to multiply numbers and "sed" to split strings.
$ echo $((1*2))
2
$ string="hello, world"
$ echo ${string/hello/goodbye}
goodbye, world $ cat foo.sh
#!/bin/bash
a="1.5"
b="0.5"
sum="$(echo "${a} + ${b}" | bc)"
echo "The sum of ${a} and ${b} is ${sum}"
$ /usr/bin/strace -q -D -w -c ./foo.sh
The sum of 1.5 and 0.5 is 2.0
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
55.53 0.001225 123 10 read
9.75 0.000215 215 1 execve
5.53 0.000122 7 18 mmap
4.03 0.000089 8 11 3 open
3.04 0.000067 7 10 mprotect
2.99 0.000066 5 13 rt_sigprocmask
2.54 0.000056 56 1 clone
2.45 0.000054 5 10 close
2.40 0.000053 5 11 rt_sigaction
1.81 0.000040 5 8 fstat
1.41 0.000031 8 4 lseek
1.22 0.000027 5 5 3 stat
0.91 0.000020 20 1 write
That was 56us to clone(2) the process and 215us to execve(2) 'bc'. All together just 12.74% of the time spent running syscalls, and an even smaller portion of the total time to launch and execute this simple example. Most of the time is sent launching bash itself at the beginning. Using a language such as python or launching a custom binary will have similar costs to to launch the program. If we're talking about a single persistent process (e.g. an interactive shell), then we're still talking about paying just 0.25ms of CPU time to perform a useful calculation. Compared to intentionally wasting time by design maximizing hash prefix guesses to "mine" Bitcoin "ain't the same fuckin' ballpark, it ain't the same league, it ain't even the same fuckin' sport"[1].However, the actual cost to launch an external program like 'bc' isn't particularly important. It could be multiple orders of magnitude slower and it would still be acceptable because we're talking ab9ut a cost that only needs to be paid a few times. Yes, compared to "full" programming languages like python, running an external program to perform a simple calculation might seem like a wasteful, half-assed solution. As Gary Bernhardt explained[2], "Half-assed is OK when you only need half of an ass."
I don't care about the cost of running 'bc' to do simple floating point calculations because I usually don't need to do floating point calculations (which are a lot harder to use safely[3] compared to simple integer math) for the type of task I would implement in a shell script. If the task required more than a few calculations (or other complex features such like a GUI), using something other language like python/ruby/C/rust would be a better tool than shell script. Learning how to choose the appropriate tools to use when solving a problem is an important skills for any engineer.
Shell scripting languages like Bourne (sh) are designed to be a glue language that you use for simple (often interactive) tasks. They are the user interface (or "IDE") of Unix. Asking why shell d9oesn't have built-in support for efficient floating point math or complex GUI features is kind of like asking why Eclipse or Visual Studio don't have a built-in spreadsheet or email client. Yes, you could probably make that happen as a half-assed hack, but it's obviously not the type of task those tools were designed for.
As for the syntax, if you find it confusing or ugly and prefer to use other tools, that's fine. There are a lot of great languages available, so use the tool that is best for you. If it had #!/bin/sh art the top, you can probably substitute any language you prefer without and problems. However, remember that for some of us Bourne shell is the easy, reasonably efficient tool we prefer to use for some problems.
[1] https://en.wikiquote.org/wiki/Pulp_Fiction#Dialogue
[2] https://www.youtube.com/watch?v=sCZJblyT_XM
[3] https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.h...
And therein lies the rub. Let's put the donkey before the cart: The reason you would not do many kinds of task in a shell script, is that shell scripts are not any good for many kinds of tasks, not because you are wrong to want to to some kinds of tasks.
The term "shell script" is an artificial construct, just like the shell scripting language itself. There is no reason you need to limit your imagination, aspirations and abilities by defining yourself as a "shell scripter" who cannot add 1.5 and 0.5 to get 2, and who cannot draw a pie chart.
Of course you should learn other languages, then you won't need to write shell scripts. Their disadvantages vastly outweigh their advantages in important ways specific to scripting and unix administration (like dealing with file names with spaces, or performing arithmetic and statistics, for examples).
Shell scripts are good for gluing together tools that do disparate things and simple automation. Most shell scripts end up becoming "real programs" once they start containing actual logic in them.