Linux main return exit

Is it OK to call pthread_exit from main?

When I call pthread_exit from main , the program never gets to terminate. I expected the program to finish, since I was exiting the program’s only thread, but it doesn’t work. It seems hung.

#include #include #include int main(int argc, char *argv[])

Process Explorer shows that the (only) thread is in Wait:DelayExecution state. According to pthread_exit documentation:

The process shall exit with an exit status of 0 after the last thread has been terminated. The behavior shall be as if the implementation called exit() with a zero argument at thread termination time.

I’m using Dev-C++ v4.9.9.2 and pthreads-win32 v2.8.0.0 (linking against libpthreadGC2.a ). The library seems to be OK (for example, calling pthread_self or pthread_create from main works fine). Is there any reason for what I’m not supposed to call pthread_exit from main ?

I know I could return or exit . I just want to know if it’s legal to terminate the main thread by calling pthread_exit .

Returning from main() is very different to running pthread_exit(). The latter will let the rest of alive threads to finish and then exit with return value 0. The former will terminate everything immediately.

4 Answers 4

Well its definately legal in the linux implementation of pthreads, see the notes section in pthreads_exit. It states

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

Further, a look at the source code here (torwads the end) shows that it roughly translates to _endthread or _endthreadex. The documentation here for those makes no mention of not calling it in the initial thread.

Then I guess it should be legal in the win32 implementation (sourceware.org/pthreads-win32/bugs.html) too. I’ve been looking for a known bug that explains this behavior, but I couldn’t find it. In my opinion, either this is a buggy behavior or there’s an actual reason I am not supposed to call pthread_exit on pthreads_win32 . Can anybody confirm any of these hypothesis?

The first printf is actually printed out, but the second one is not (as expected). The problem is that the program will not terminate. It simply gets kind of frozen.

I finally found the problem. I think it was some kind of malware on my operating system. I’ve just cleaned it up with an antispyware tool and now it works as expected. Oh, my. I feel really stupid. @torak I’m going to accept your answer. Thanks for your help!

This completely legal and intended behavior. The whole process only ends when either all threads terminate or exit is called explicitly or implicitly.

A normal return from main is equivalent to a call to exit . If you end main with pthread_exit your are saying explicitly that you want the other threads to continue.

It’s fine to use pthread_exit in main. When pthread_exit is used, the main thread will stop executing and will remain in zombie(defunct) status until all other threads exit.

If you are using pthread_exit in main thread, cannot get return status of other threads and cannot do clean-up for other threads (could be done using pthread_join(3)). Also, it’s better to detach threads(pthread_detach(3)) so that thread resources are automatically released on thread termination. The shared resources will not be released until all threads exit.

Читайте также:  Обновить кали линукс через командную строку

Its ok to use when not allocating resources in the main thread, clean-up is not needed. Below code shows using pthread_exit in the main thread. The second printf in main is not printed as main thread exits after calling pthread_exit. Ps output shows the defunct main thread.

#include #include #include #include #include void *functionC(void *); int main() < int rc; pthread_t th; if(rc = pthread_create(&th, NULL, &functionC, NULL)) < printf("Thread creation failed, return code %d, errno %d", rc, errno); >printf("Main thread %lu: Sleeping for 20 seconds\n", pthread_self()); fflush(stdout); sleep(20); pthread_exit(NULL); printf("Main thread %lu: This will not be printed as we already called pthread_exit\n", pthread_self()); exit(0); > void *functionC(void *)
Main thread 140166909204288: Sleeping for 20 seconds Thread 140166900684544: Sleeping for 20 second Thread 140166900684544: Came out of first and sleeping again CThread 140166900684544: Came out of second sleep 
root@xxxx-VirtualBox:~/pthread_tst# ps -elfT |grep a.out 0 S root 9530 9530 9496 0 80 0 - 3722 hrtime 17:31 pts/1 00:00:00 ./a.out 1 S root 9530 9531 9496 0 80 0 - 3722 hrtime 17:31 pts/1 00:00:00 ./a.out 0 S root 9537 9537 2182 0 80 0 - 5384 pipe_w 17:31 pts/0 00:00:00 grep --color=auto a.out root@xxxx-VirtualBox:~/pthread_tst# ps -elfT |grep a.out 0 Z root 9530 9530 9496 0 80 0 - 0 - 17:31 pts/1 00:00:00 [a.out] 1 S root 9530 9531 9496 0 80 0 - 4258 hrtime 17:31 pts/1 00:00:00 ./a.out 0 S root 9539 9539 2182 0 80 0 - 5384 pipe_w 17:31 pts/0 00:00:00 grep --color=auto a.out` 

Please check blog Tech Easy for more information on threads.

Источник

Return и exit, в чем разница?

В чем разница между return и return false/true
Привет всем. Вот подскажите плиз) return; return false; return true; расскажите пожалуйста.

В чем разница между quit(),exit() и terminate() ?
Читал описание класса QThread и не могу понять в чем собствнно различие функций quit(),exit() и.

Операторы Exit, Close, Application.Terminate в чем разница между ними?
Хочу понять разницу между этими операторами. Например, оператор Application.Terminate выходит из.

замена exit(0) на return
необходимо заменить exit(0) из данного куска кода на return в main, используя при этом.

Лучший ответ

Сообщение было отмечено Матричный бог как решение

Решение

Эксперт CАвтор FAQ

exit — это функция, которая завершает программу, откуда бы ни была вызвана. return — это оператор, который завершает работу текущей функции (т.е. передаёт управление в точку вызова текущей функции)

Если речь идёт о функции main, то return и exit по смыслу можно считать, что одно и то же. В случае выхода из main’а оператором return управление будет передано в системную часть в точку вызова main, а оттуда будет вызвана функция exit

Однако когда речь идёт о Си++, то разница есть. По оператору return будут вызваны деструкторы всех локальных живых объектов. А по exit — ничего вызвано не будет. Т.е. в C++ return и exit в main’е в общем-то отличаются поведением (в отличие от C)

Источник

What is the difference between exit and return?

What is difference between return and exit statement in C programming when called from anywhere in a C program?

I removed the ‘close as duplicate’ because the chosen duplicate is tagged with both C and C++ and there is no need to confuse people with the C++ issues (which are different from, though vaguely similar to, the C issues). The duplicate was return statement vs exit() in main()?

Читайте также:  Java security settings linux

5 Answers 5

  • return returns from the current function; it’s a language keyword like for or break .
  • exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit() .

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret); . The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

If you execute this program it prints:

#include #include void f() < printf("Executing f\n"); exit(0); >int main()

If you execute this program it prints:

You never get «Back from f». Also notice the #include necessary to call the library function exit() .

Also notice that the parameter of exit() is an integer (it’s the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).

The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.

Last point, exit() come in two flavors _exit() and exit() . The difference between the forms is that exit() (and return from main) calls functions registered using atexit() or on_exit() before really terminating the process while _exit() (from #include , or its synonymous _Exit from #include ) terminates the process immediately.

Now there are also issues that are specific to C++.

C++ performs much more work than C when it is exiting from functions ( return -ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won’t care much of the state of a program after the processus stopped, hence it wouldn’t make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream locally created won’t be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

This won’t happen if you are using the good old C FILE* streams. These will be flushed on exit() . Actually, the rule is the same that for registered exit functions, FILE* will be flushed on all normal terminations, which includes exit() , but not calls to _exit() or abort().

You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.

Destructors of static C++ objects (globals) will be called if you call either return from main() or exit() anywhere in your program. They wont be called if the program is terminated using _exit() or abort() . abort() is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert() macro only active in debug mode.

Читайте также:  Linux usb iphone tether

When is exit() useful ?

exit() means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won’t allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).

Direct calls to exit() are especially bad if done in libraries as it will doom the library user and it should be a library user’s choice to implement some kind of error recovery or not. If you want an example of why calling exit() from a library is bad, it leads for instance people to ask this question.

There is an undisputed legitimate use of exit() as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.

Источник

Given a main function and a cleanup function, how (canonically) do I return an exit status in Bash/Linux?

Context: I have a bash script (a wrapper for other scripts, really), that does the following pseudocode:

do a main function if the main function returns: $returncode = $? #most recent return code if the main function runs longer than a timeout: kill the main function $returncode = 140 #the semi-canonical "exceeded allowed wall clock time" status run a cleanup function if the cleanup function returns an error: #nonzero return code exit $? #exit the program with the status returned from the cleanup function else #cleanup was successful . 

Question: What should happen after the last line? If the cleanup function was successful, but the main function was not, should my program return 0 (for the successful cleanup), or $returncode , which contains the (possibly nonzero and unsuccessful) return code of the main function? For a specific application, the answer would be easy: «it depends on what you need the script for.» However, this is more of a general/canonical question (and if this is the wrong place for it, kill it with fire): in Bash (or Linux in general) programming, do you typically want to return the status that «means» something (i.e. $returncode ) or do you ignore such subjectivities and simply return the code of the most recent function? This isn’t Bash-specific: if I have a standalone executable of any kind, how, canonically should it behave in these cases? Obviously, this is somewhat debatable. Even if there is a system for these things, I’m sure that a lot of people ignore it. All the same, I’d like to know. Cheers!

Источник

Оцените статью
Adblock
detector