svn commit: r355318 - head/sbin/newfs_msdos

Xin Li delphij at FreeBSD.org
Wed Dec 4 08:52:01 UTC 2019


On 12/3/19 14:02, Conrad Meyer wrote:
> Hi Xin Li,
> 
> Is there a reason to prefer exit() over returning from main?  I have

No, this should be case-by-case (and also assumes you are using C and
not C++).

The two are actually subtly different (return means teardown main's
stack first, then implicitly call exit from C runtime, while exit()
would terminate immediately).

If the command is meant to be used as a built-in module of something
else, like the case of kill(1) builtin of sh(1), then one must not use
exit() and also need to pay special attention to not exit() implicitly,
because the caller will not fork() prior to calling the aliased main()
function for performance reasons.

For other cases, using exit() might be a good idea, because it's easier
to find the exit points especially if one is following sysexits(3)
values.  Another reason is that if one allocates memory in main but not
free them (these shouldn't be free'ed because the kernel would unmap all
pages upon exit), return would mean these memory would be leaked: these
are legitimate issues when main() would be called by someone else.  With
an explicit exit(), these memory are never leaked because stack frame of
main() remains valid before the final _exit(2) call.

> not surveyed the source tree, but I suspect most programs in base exit
> by returning from main rather than explicit exit(3).> Thanks,
> Conrad
> 
> On Mon, Dec 2, 2019 at 11:03 PM Xin LI <delphij at freebsd.org> wrote:
>>
>> Author: delphij
>> Date: Tue Dec  3 07:03:25 2019
>> New Revision: 355318
>> URL: https://svnweb.freebsd.org/changeset/base/355318
>>
>> Log:
>>   Explicitly exit() instead of return in main().
>>
>>   MFC after:    2 weeks
>>
>> Modified:
>>   head/sbin/newfs_msdos/newfs_msdos.c
>>
>> Modified: head/sbin/newfs_msdos/newfs_msdos.c
>> ==============================================================================
>> --- head/sbin/newfs_msdos/newfs_msdos.c Tue Dec  3 07:01:28 2019        (r355317)
>> +++ head/sbin/newfs_msdos/newfs_msdos.c Tue Dec  3 07:03:25 2019        (r355318)
>> @@ -189,7 +189,7 @@ main(int argc, char *argv[])
>>             err(1, NULL);
>>      }
>>      dtype = *argv;
>> -    return !!mkfs_msdos(fname, dtype, &o);
>> +    exit(!!mkfs_msdos(fname, dtype, &o));
>>  }
>>
>>  /*


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: OpenPGP digital signature
URL: <http://lists.freebsd.org/pipermail/svn-src-head/attachments/20191204/042f69a0/attachment.sig>


More information about the svn-src-head mailing list