سؤال

I'm writing a university project. Writing in standard C99. One of the requirements is the lack of exit(); function. Is it possible to implement a similar function? I tried to make a function that calls main with a minus argc to detect exit. It was a stupid attempt, because the first main continues.

Just the description of the project specified that the scores will be reduced for the use of exit by exit().I understand that it asks me to code running through pointers and returns an error in the return values ​​of the function. I'm more interested in the practice. Only for myself.

هل كانت مفيدة؟

المحلول

I think you misunderstood the requirement: They probably said something like do not use exit(). This does not mean you are supposed to implement your own exit(), quite to the contrary: they probably mean that the only exit-point of your program shall be the end of your main-function (or a return-statement within the main function) which is considered good programming style.

نصائح أخرى

exit() is a system level facility that you can't implement on your own without knowing how the operating system implements it (Linux? Windows? embedded system?) works. As Daniel Fischer mentioned, you could call abort() which will basically do the same thing that exit will do and quit the program.

There are other "hacks" to get your program to abort without calling exit() explicitly, but these are just hacks and should not be used in production code.

  1. Create a C++ function with C linkage and throw an exception

    extern "C" MyExit() { throw std::exception(); }

  2. Call signal() with SIGKILL

  3. Call abort()

  4. Write some assembly code to unwind the call stack until it gets to the function that called main and insert the return value in to the proper return register and go from there. I don't think you can do this in pure C, as the ABI is not accessible directly. But at least this would be only method that doesn't involve the operating system (just the ABI).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top