How to conceal a segmentation fault in a bash script

北城以北 提交于 2020-01-24 09:56:26

问题


I use a program that works properly and results in desirable output at the end of its operation with no memory leak or any other specific issue, but then it issues a segmentation fault at the point it exits. I have been trying to hide this harmless but annoying error from the end user when using this program by redirecting the standard error to Null:

program options >file 2>/dev/null

But this doesn't work and the error shows up in the middle of the script's outputs each time I run the program. What is exactly happening here, and how can I hide the unwanted error? I'm on Yosemite.


回答1:


From the Bad Idea Department:

program options >file 2>/dev/null | cat

It seems that bash won’t complain about segmentation faults in programs whose output is piped elsewhere. So just pipe your output anywhere. cat is a good choice, since it just echos the text it was sent. Or pipe to the null command, :, so you can put an emoji in your script:

program options >file 2>/dev/null |:

It should be obvious that this can hide other, more severe problems, and so you should fix the segmentation fault if at all possible.




回答2:


My advice is to fix the error.

The problem with hiding the error is twofold:

  • The error might not be harmless. Until you have identified the real cause, you cannot be sure.

  • Anything that you implement to hide this error is liable to also hide other errors ... with may not exist yet, or may exist and not have manifested themselves yet.


The program is not mine, and I have no idea how to fix it.

You need to discuss this with the developer / supplier. Either get the source code and fix it yourself, or put pressure on them to fix it. (There are various ways to do the latter ... depending on the nature of the software and support arrangements.)


If you really need a workaround, then take a look at how bash handles signals. Based on the fact that redirection does not work, I suspect that what is happening is that bash is generating the message itself, and writing it to the console stream. A plausible way to change this is to implement a custom signal handler for SIGSEGV in the bash script. This approach has the advantage (over other "hacks") of being a bit selective.

Of course, there are other more "brutal" ways:

  • Run the application in a subshell, and redirect the subshell's stderr in the main wrapper script.

  • Pipe to true to suppress the signal reporting. (See other answer. I didn't know you could do that.)



来源:https://stackoverflow.com/questions/28521938/how-to-conceal-a-segmentation-fault-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!