Shuzheng Shuzheng - 2 years ago 69
C Question

Does it make sense to exit(0) after a call to execl()?

Consider the following code:

close(channel_data->pty_master);

if (login_tty(channel_data->pty_slave) != 0) // new terminal session
{
exit(1); // fail
}

execl("/bin/sh", "sh", mode, command, NULL); // replace process image
exit(0);


According to the documentation of
execl()
, the current process image is being replaced and the call returns only on errors.

But why call
exit()
after a call to
execl()
if the process image is replaced?

Answer Source

It does make sense to call exit after some exec(3) function because they can fail (e.g. when execve(2) is failing). The execve(2) page lists a number of failure reasons.

It should better be exit(EXIT_FAILURE) or some other (non 0) exit code, and I recommend calling perror just before that exit. As explained by PSKocick there are good reasons to call _exit (but his arguments could be reversed, one would want to run atexit and standard fflushs by using exit instead).

In your case, failure is unlikely, but imagine however if some other process has removed /bin/sh (e.g. the sysadmin making the stupid mistake of running /bin/rm -rf . in the root directory, or in /bin/, perhaps in some other terminal window).

Still that execve could also fail when system resources are (temporarily) exhausted, e.g for

ENOMEM Insufficient kernel memory was available.

And (in rare cases) this could even happen for /bin/sh;

BTW your exec usage would probably fail (with E2BIG) if (by mistake) command was a string of a million of non-null bytes.

As a general coding rule, all important system calls should be checked against failure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download