This is the correct answer -- when you fork the process yourself, you don't have to guess about it dying, you get SIGCHLD and can handle it accordingly.
If you use daemontools, this code is already written for you.
regex background: [abc] matches any of 'a', 'b', or 'c'. [m] matches only 'm'.
It works because the text to match is no longer included in the command line invoked to do the matching. Whether or not 'grep [m]ysqld' appears in the list produced by ps is irrelevant, as [m]ysqld does not match "m]ysqld". i.e. the 'm' matches, but then the match fails when it hits ']'.
tl;dr It's just a short way of matching "mysqld" without the matching pattern itself being "mysqld".
Sounds very hacktastical to count the entries as a way to know if the service is alive.
If I found someone doing this on one of my production database machines, I think I'd have to dig out the paintball gun and start chasing them around, especially if the person run around with the title of sysadmin. (I'd cut a slight bit of slack if they were a webdev.)
If it restarted every few hours and the test executed once a minute, then the bug would appear only once in a hundred executions. It's a good post, I think I could have made the same mistake easily.
I'd never noticed it. I worked in a unix shell for a while, but I used to use ps piped to grep. But I suspect I often used 'grep -v' to filter the output anyway when I really needed just the non-grep lines.
Unmentioned is that there could easily be other 'mysqld' processes running on your box, even without someone screwing with you -- a lot of commercial apps bundle their own copy, even on the desktop (like Acrobat 8 Pro).
And best way, that will set your mind at ease even if you’re worried that “mysql is running but not responding; it is stuck”: connect to MySQL and issue SELECT 1, SELECT NOW(), SELECT something.
Fortunately this is easy:
$ echo "select now();" | mysql
now()
2009-10-05 19:24:22