Program Runs Even Though I Return -1? - c++

I am running this very simple c++ code:
int main()
{
return -1;
}
But when I compile it with g++ and run it (on ubuntu 14.04) it goes through and I get no errors. The book that I am reading, "C++ Primer" says that I should receive an error, so I was wondering if someone could show me what I am doing wrong.

Your program runs normally, then returns a status of -1 to the environment. If you don't look at that status, you're not going to see any indication of an error.
If you're running from the bash shell, you can do something like:
if ./my_program ; then
echo Success
else
echo Failure
fi
or, on one line:
if ./my_program ; then echo Success ; else echo Failure ; fi
or, if you want to be obscure:
./my_program && echo Success || echo Failure
More simply:
./my_program
echo $?
Incidentally, returning a status of -1 is not a portable way to indicate failure. I suggest adding #include <cstdlib> to the top of your program and using return EXIT_FAILURE;. (The value of EXIT_FAILURE is typically 1, but it will be whatever it needs to be to denote failure on the system you're using.)

The code that you've written here is perfectly legal C++. The program runs and then signals an exit code of -1. On some operating systems, if a program terminates with a nonzero exit code, the OS will report an error to the user indicating that something weird happened. On Ubuntu, though, programs that terminate with nonzero exit codes don't trigger an explicit error message, so what you're seeing is the expected behavior.

The return value of main is what's called an exit code. If you run your program from a shell (such as bash on a Unix system or the CMD on Windows), you can examine the exit code. By convention, nonzero exit codes usually imply that something erroneous happened. For instance, your g++ compiler outputs a nonzero exit code if there's a compile error and 0 if everything goes correctly.
Since you said you're on Ubuntu, I assume you're using either bash or dash to run this program. Try running the program and then do echo $? after running the program. You should see the exit code your program returned.

Related

What is the purpose of echo command after executing a program?

Why do we exit issuing an echo command while executing a program?
As far as I know, the echo command for console windows is:
$ echo $
And for windows is:
$ echo %ERRORLEVEL%
When the child process ends, the set variable ERRORLEVEL contains an integer returned by it. ERRORLEVEL is measured 0 if the process was successful (i.e. return 0). OTOH, 1 or greater if the process encountered an error.
However, I don't know what do you exactly mean by:
echo command after executing a program
I never ran this command neither I've seen anywhere.

How to make LLDB quit on success, wait on failure?

This is the Clang version of:
Make gdb quit automatically on successful termination?
How to have gdb exit if program succeeds, break if program crashes?
Running my application many times, programmatically, over a large number of possible inputs, I've occasionally encountered a segmentation fault.
I'd like each test invocation to be run under lldb so that I can get a backtrace for further debugging. If an invocation exits without a crash, I'd like lldb to automatically quit so that the test harness progresses to the next iteration. This way I can set the whole thing off over lunchtime and only have the suite interrupted when something crashes.
Bonus points for having lldb auto-quit in all cases, but first print a backtrace if the program crashed.
I'm currently able to automate at least the initial run command:
lldb -o run -f $CMD -- $ARGS
I'm having difficulty finding an online command reference but it looks like the -batch command line option will get you the basic "exit on success/prompt on fail" behaviour.
For a backtrace and auto-quit on failure I think you need the --source-on-crash option...
-K <filename>
--source-on-crash <filename>
When in batch mode, tells the debugger to source this file of lldb
commands if the target crashes.
So, create the command file with something like...
echo -e 'bt\nquit' > lldb.batch
and then invoke as...
lldb --batch -K lldb.batch -o run -f $CMD -- $ARGS

shell process creation error in system() command

I have this piece of code in my c++ project:
std::string run_command = "build/executable input.txt";
std::string copy_command = "cp output.txt output_1.txt;";
int status1= system(run_command.c_str());
int status2=system(copy_command.c_str());
It perfectly runs in my pc, but doesn't work in my laptop. Both system calls return -1, meaning that there is a problem in shell process creation. What do you think is the problem?
As reported by manual:
The value returned is -1 on error (e.g., fork(2) failed), and the
return status of the command otherwise. This latter return status is
in the format specified in wait(2). Thus, the exit code of the command
will be WEXITSTATUS(status). In case /bin/sh could not be executed,
the exit status will be that of a command that does exit(127).
So, path should be correct. Try to add some print debug in your scripts.
Maybe you are referring to resources or libraries that in your laptop does not exist.
try using ptrace and print errno (http://man7.org/linux/man-pages/man3/errno.3.html) to find the reason as to why system call failed. This is another resource to steer you on why the system call failed http://bytes.com/topic/c/answers/217348-get-system-error-message
P.S.
I'm not entirely confident in writing c++ systems programs but i build a shell in C and printing errno helps. I definitely recommend using ptrace as well as monitoring whether the OS has enough resource to allocate new processes.

How can I catch exception on bash file exit unnormally?

Here I get a bash file b.sh:
#!/bin/sh
if [ ! -f somefile.txt ]; then
..................
fi
in the bash file ,I try to check whether somefile called "somefile.txt" exist, if not, I would consider it as an error and exit.
And I run this bash file in c++:
::system("sh b.sh")
What should I fill in the "..............." in that bash file and what should I do in c++ code to catch exception when the "somefile.txt" is not found.
Put:
exit 1
in the script -- by convention, any non-zero exit code is considered failure.
In the C++ code, system() returns the termination status of the command. See the documentation of wait() for details of interpreting this, or you can just check if it's non-zero if you want to know if there was any error.

How to have gdb exit if program succeeds, break if program crashes?

I seem to have some kind of multithreading bug in my code that makes it crash once every 30 runs of its test suite. The test suite is non-interactive. I want to run my test suite in gdb, and have gdb exit normally if the program exits normally, or break (and show a debugging prompt) if it crashes. This way I can let the test suite run repeatedly, go grab a cup of coffee, come back, and be presented with a nice debugging prompt. How can I do this with gdb?
This is a little hacky but you could do:
gdb -ex='set confirm on' -ex=run -ex=quit --args ./a.out
If a.out terminates normally, it will just drop you out of GDB. But if you crash, the program will still be active, so GDB will typically prompt if you really want to quit with an active inferior:
Program received signal SIGABRT, Aborted.
0x00007ffff72dad05 in raise (sig=...) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
64 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
in ../nptl/sysdeps/unix/sysv/linux/raise.c
A debugging session is active.
Inferior 1 [process 15126] will be killed.
Quit anyway? (y or n)
Like I said, not pretty, but it works, as long as you haven't toggled off the prompt to quit with an active process. There is probably a way to use gdb's quit command too: it takes a numeric argument which is the exit code for the debugging session. So maybe you can use --eval-command="quit stuff", where stuff is some GDB expression that reflects whether the inferior is running or not.
This program can be used to test it out:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
if (time(NULL) % 2) {
raise(SIGINT);
}
puts("no crash");
return EXIT_SUCCESS;
}
You can also trigger a backtrace when the program crashes and let gdb exit with the return code of the child process:
gdb -return-child-result -ex run -ex "thread apply all bt" -ex "quit" --args myProgram -myProgramArg
The easiest way is to use the Python API offered by gdb:
def exit_handler(event):
gdb.execute("quit")
gdb.events.exited.connect(exit_handler)
You can even do it with one line:
(gdb) python gdb.events.exited.connect(lambda x : gdb.execute("quit"))
You can also examine the return code to ensure it's the "normal" code you expected with event.exit_code.
You can use it in conjuction with --eval-command or --command as mentioned by #acm to register the event handler from the command line, or with a .gdbinit file.
Create a file named .gdbinit and it will be used when gdb is launched.
run
quit
Run with no options:
gdb --args prog arg1...
You are telling gdb to run and quit, but it should stop processing the file if an error occurs.
Make it dump core when it crashes. If you're on linux, read the man core man page and also the ulimit builtin if you're running bash.
This way when it crashes you'll find a nice corefile that you can feed to gdb:
$ ulimit -c unlimited
$ ... run program ..., gopher coffee (or reddit ;)
$ gdb progname corefile
If you put the following lines in your ~/.gdbinit file, gdb will exit when your program exits with a status code of 0.
python
def exit_handler ( event ):
if event .exit_code == 0:
gdb .execute ( "quit" )
gdb .events .exited .connect ( exit_handler )
end
The above is a refinement of Kevin's answer.
Are you not getting a core file when it crashes? Start gdb like this 'gdb -c core' and do a stack traceback.
More likely you will want to be using Valgrind.