About the exit() function in C++ - c++

The getche() function doesn't terminate the program properly, so I want to try exit(int status) function. How does it work in Turbo C++ programming language? I cannot understand the explanation in related help modules and I seek for a better explanation... E.g. what does function's parameter consist of? Thanks in advance!

Not 100% sure what you mean by this. The parameter to the exit function (the "int status") is a number that gets returned to the shell. Traditionally, this is zero if your program was successful and >0 if the program failed for some reason. The function will clean up various things and then exit your program.

Well. Functions like getch.. usually get a character from the keyboard or standard input. They are sometimes used at the end of programs like this
int main() {
// do many stuff...
// ...
getch();
}
The getch/getche (i don't know what the e stands for in turbo-c++) are then used to give the user the change to see the output of the program, before the terminal windows closes (usually that happens in windows). Note that there is a portable function called getchar in C and C++ that does also do that job (waits for an enter in addition, but that won't cause a harm here).
But it is not used to terminate the program. After a key is pressed, control continues and then after main finished, the program exists. C++ and recent C versions insert a return 0; implicitly after the last statement of the main function (0 stands for "succesful"). This means your main function returns a value of 0 back to the OS. But you can return other values if you write the return explicitly and put another value there. That value is what exit expects. It terminates your program, and returns the given value back to the OS.
int main() {
// some stuff...
exit(42);
// other stuff (note: never reached!)
}
That program will return a value of 42 to the OS. Normally you just return 42; there and it has the same effect (*).
(*) Well, not entirely: If you have local variables, the destructor of those are not called if you use exit. But they are cleanly destructed and destructors are called when you use return n;. Therefor, prefer return n; in main when you can. exit called in other functions than your main will terminate your program too, so it can be required to use that instead, because return there will just return from those specific functions and do not at all terminate the program.

The parameter is an integer status code that is passed back to the invoking shell as the exit status of the process. Exit itself should exit the process an clean up any open resources that your process is using.

The parameter to Exit() is an int that indicates the reason or status of the exiting process.
Boy, that didn't sound good. Let me try again: It's a value that is passed back to either the starting process (the process that used CreateProcess() or ShellExecute() to launch the one that's exiting), or, in the case of a console app a value to the command shell that can be accessed via ERRORLEVEL.
It's typical to set status = 0 if you're exiting normally, another value (that can have meaning if you want to the process that receives it) to indicate errors or problems.

The parameter is an integer status code that is passed back to the invoking shell as the exit status of the process. Exit itself should exit the process an clean up any open resources that your process is using.

More Info on "exit" Function
"exit" function Terminates the process normally, performing the regular cleanup for terminating processes.
First, all functions registered by calls to "atexit" are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.
The value supplied as an argument to exit is returned to the operating system ( the host environment) as the program's return code or exit code. By convention, a return code of zero means that the program completed successfully.
Hope this clears your doubt.

Related

What is the difference between "stop" and "exit" in Fortran?

What is the difference between stop and exit in Fortran?
Both can terminate the program immediately with some error information.
exit in Fortran is a statement which terminates loops or completes execution of other constructs. However, the question is clearly about the non-standard extension, as either a function or subroutine, offered by many compilers which is closely related to the stop statement.
For example, gfortran offers such a thing.
As this use of exit is non-standard you should refer to a particular implementation's documentation as to what form this takes and what effects it has.
The stop statement, on the other hand, is a standard Fortran statement. This statement initiates normal termination of execution of a Fortran program (and can be compared with the error stop statement which initiates error termination).
Other than knowing that terminating (normally) execution of the program follows a stop statement and that there is a stop code, the actual way that happens are again left open to the implementation. There are some recommendations (but these are only recommendations) as to what happens. For example, in Fortran 2008 it is suggested that
the stop code (which may be an integer or a string) be printed to an "error" unit;
if the stop code is an integer it be used as the process exit status;
if there is no stop code (or it's a character) zero be returned as the exit status.
The above is fairly vague as in many settings the above concepts don't apply.
Typically in practice, exit will be similar to the C library's function of that name and its effect will be like stop without a stop code (but still passing the given status back to the OS).
In summary, Fortran doesn't describe a difference between stop and exit. Use of exit (for termination) is non-portable and even the effect of stop is not entirely defined.
stop is a fortran statement but exit is a function that just happens to terminate the program.
The stop statement will output its argument [which can also be a string] to stderr
stop 123
and it will return a zero status to the parent process.
Whereas exit is a function and must be called like any other. It will also be silent (i.e. no message):
call exit(123)
and the argument to exit will be returned to the parent process as status

Who receives the value 0 when we write return 0 [duplicate]

This question already has answers here:
What should main() return in C and C++?
(19 answers)
What is the purpose of the returning of a value from main() in C/C++? [duplicate]
(5 answers)
Closed 9 years ago.
int main()
{
return 0;
}
Who receives the value 0 after executing the main function? and what is this value used for after that?
The effect of executing a program is the same as a single call of:
std::exit(main(/* args */))
So the return value of main is the single argument of exit, whatever that means to your system.
Note that the standard only defined two return values, EXIT_SUCCESS and EXIT_FAILURE. Returning zero is equivalent to returning EXIT_SUCCESS. Everything else is implementation defined.
On Unix(like) systems, you can signal exit status to your shell (assumnig bash):
$ ./your-program
$ echo $?
0
In bash, $? is the exit code of the previous command.
Returning a value from the main() function is equivalent to calling exit() with that value. So your code is similar to:
int main() {
std::exit(0);
}
The exit status is returned to the runtime library. It can be accessed by the parent process that invoked the program; on Unix this is done using the wait() family of calls. If you run the program from a Unix shell, the exit status is put in the variable $?, or you can test it using control statements like if or while.
The operating system may use this value. In most operating systems, you can query this value after the program has run. How you do this depends on the operating system.
main's return value is passed to process calling your program.
The program calling your program. In the above case it is the OS shell or a batch file/script executing your program.
The return value is passed to std::exit as argument status, which will then do some tidying up and return an exit status to the host environment:
Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an
implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
Consider a program the executes child programs. Many times this would be a shell/terminal/console. When a child exits it can tell it's parent that it has finished and whether it was successful.
consider the program cd which changes directory and rm which removes some files. If you would write a program that cd's to a directory, and subsequently removes all files with rm * then it is really important that the shell/console/terminal is able to tell whether the cd command was successful, because otherwise the contents of a current directory could be removed.
The shell calls e.g. waitpid on the cd command and examines what value is returned. And based on that return value a shellscript programmer can deside to either call rm or do some error handling.

C++ return at the end of main() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was thinking about implementing my own exit() function for educational purpose, only. I know you can manipulate addresses if the OS lets you (for example the OS won't let you manipulate the address 0, it would cause a crash).
So I thought why not sending 0 to that address return 0 returns to.
int main(){
// code...
return 0;
}
The return 0 returns a 'success' to the OS, right? But which address is it? How do I get it? And is the actual exit() from the C standard library implemented this way?
When you return 0, you do not return to an address. You are returning the value 0. When a process returns the value 0, it is considered to be normal termination. You can return a non-zero value (up to 255) that may be interpreted by the calling process as a message.
Let us look at this with an example command grep foobar fubar. It will return 0 (success) if there is the pattern foobar in the file fubar. It will return 1 if there is no foobar in the file fubar. It will return 2 when there is no file named fubar. The rturn value could be interpreted in the script that makes this command to evaluate the success or reason for failure.
The exit code is (eventually) stored into the Process Control Block so that the OS can report the result value to other processes.
See http://www.cs.auckland.ac.nz/compsci340s2c/lectures/lecture06.pdf
However, the return statement isn't what does this. Your runtime library is actually calling main more-or-less like a normal function, gets the return value (on Intel, a return value of type int would be stored in the EAX register), and then requests that the kernel write it to the TCB. exit() also invokes the kernel to write this member of the TCB.
The return 0; in main works like a return anywhere; it
returns to the place from which it was called. When you start
a program, the system does not start it at main, but at some
start-up address which does a lot of initializations, and then
something like:
exit( main(/*...*/) );
In other words, exit does not simulate a return from main;
returning from main calls exit. And exit then does a lot of
shutting down, before calling some system specific function
which tells the system to stop the process (_exit under Unix).
You cannot implement exit yourself, because you have no way of
finding the information it needs: the list of functions
registered with atexit which need to be called, the list of
destructors of objects with static lifetime, etc.
I think the main confusion here is the notion that that main is the first and last thing that happens in C++ program. Whilst it is [1] the first part of YOUR program, there is usually some code in the application that sets up a few things, parses command line arguments, opening/initialization of standard I/O (cin, cout, etc) and other such things, which happen BEFORE main is called. And main is essentially just another function, called by the C++ runtime functionality that does that "fix things up before main".
So, when main returns, it goes back to the code that called it, which then cleans up the things that need cleaning up (closing standard I/O channels, and many other such things), before actually finishing up by calling some OS function to "terminate this process". As part of this "terminate this process" functionality is (in most OS's) a way to signal "success or failure" to the OS, so that some other process monitoring the application can determine "if all is well or not". This is where, eventually, the 0 (or 1 if you use return 1; in main) ends up.
[1] If there are static objects with constructors that are part of the user's code, then these will be performed before any code in main [or at least, before any code in main that belongs to the user's application] is executed.
Your confusion is because of not understanding what return does. Take this function for example:
int add(int x, int y)
{
return (x + y);
}
The return in above function and the return statement at the end of your main function are exactly the same, from a language standpoint they mean the same. The meaning of that is to return an integer to the caller. What the caller makes out of this value is completely another thing which depends on the caller's intention of calling said function. Say I can call add(7, 9); to add two GPA grades while another programmer might call it to find the sum of all the money in a couple of bank accounts.
Now main is treated as a special function since it is the first function the operating system, or more specifically its loader, calls to being your program. After your program completes, whatever main returns might mean anything based on the OS's semantics. This value has nothing to do with any memory address.
Aside: According to the standard, in C++ (and C99 onawards) the return 0; statement can be omitted to mean a successful termination of the program.
If m understanding is correct, there will be a SIGCHLD signal that would be sent on exit to main shell which contains the return value... This should happen when the PCB is destroyed by the kernel...
But if you want to hook up certain functionality while exiting from the code, you can register a handler at atexit() as per POSIX implementation..
I dont think you can modify how the return valur propagates at user level, since the control of the program reaches the PC in another process ( of which you dont have access to).
If your C++ abi library implements the symbol __cxa_atexit you can use atexit
AFAIK the language doesn't really offer other safe ways to do something that is user-defined when a program stops the execution.
When you have a function, it has a type. It can be int, void, or other. If the function is not void, then it has to return a value. In our case, the return value of main is int, which is usually a return code. The convention is that if it is 0, then there was no error, while other values are error codes.

how to exit from a function but not from main()

Does C/C++ support terminating a program from a subroutine function i.e not main?
So far I only found that exit and abort allow a user to terminate current function or process.
If I'm not in main function, is there a way to terminate the whole program?
If you are not in main() and in other function then also you can call exit() or abort() it will terminate your whole process.
where exit() will do required clean up where abort() will not perform that.
exit(0) or exit(1)
If this is 0 or EXIT_SUCCESS, it indicates success.
If it is EXIT_FAILURE, it indicates failure.
ref: See here
since you're talking C++, consider std::terminate
u now, for “Does C/C++ support terminating a program from a subroutine function i.e not main?”
by default std::terminate calls abort, but this is configurable by installing a handler via std::set_terminate
void exit (int status)
Above method Terminates the process normally, performing the regular cleanup for terminating programs.
Normal program termination performs the following (in the same order):
Objects associated with the current thread with thread storage duration are destroyed (C++11 only).
Objects with static storage duration are destroyed (C++) and functions registered with atexit are called.
All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed.
And after that Control is returned to the host environment.
As it terminates the calling process, becuase your function is part of same process, so using exit() in that will terminate the program.
It can only be possible if you called that function from main function. And from that function from which you want to terminate the program return a value for terminating the program for example -1.
Example:
void main()
{
//Call to a function
int i = functionFromMain();
if(i == -1)
{
//Terminate Program
}
}

Exiting from C++ Console Program

I currently have a program which has the following basic structure
main function
-- displays menu options to user
-- validates user input by passing it to a second function (input_validator)
-- if user selects option 1, run function 1, etc
function1,2,3,etc
-- input is requested from user and then validated by input_validator
-- if input_validator returns true, we know input is good
Here is my problem. I want to allow the user to quit at any point within the program by typing '0'. I planned on doing this with some basic code in input_validator (if input = 0, etc).
This would appear to be simple, but I have been told that using quit() will result in some resources never been released / etc. I cannot simply do a 'break' either -- it will result in my program simply returning to the main function.
Any ideas?
One possibility would be to do it by throwing an exception that you catch in main, and when you catch it, you exit the program. The good point of throwing an exception is that it lets destructors run to clean up objects that have been created, which won't happen if you exit directly from elsewhere (e.g., by using exit()).
exit()
Terminates the process normally,
performing the regular cleanup for
terminating processes.
First, all functions registered by
calls to atexit are executed in the
reverse order of their registration.
Then, all streams are closed and the
temporary files deleted, and finally
the control is returned to the host
environment.
This hasn't been true for any kind of mainstream operating system for a long time. The OS ensures that all kernel resources are released, even if the program didn't explicitly do so. Calling abort() or exit() from anywhere in your code is fine.
exit(int exitCode) - defined in stdlib.h / cstdlib - you'd probably want to exit(0); // normal termintation.
exit() will not call your destructors, so you might want to consider using an exception handler instead.
If you have things like open but unflushed files, the OS will close the file handles, but won't flush any unwritten data.
You have to design your menu system so that a status can be passed back to the previous method, unwinding until code in the main function is executed. Similar issues apply to back or previous screen buttons.
Taking a step back and looking at the Big Picture, the unwinding technique looks very similar to C++ exception handling strategy. I suggest using exceptions for cases that don't follow the normal flow of execution, such as main menu, and previous menu.
Try it out.