5

From the fork(2) man page:

RETURN VALUE
   On success, the PID of the child process is returned in the parent, and
   0 is returned in the child.  On failure, -1 is returned in the  parent,
   no child process is created, and errno is set appropriately.

I am wondering about the reasons that would make a fork call fail. What are the case scenarios where fork returns -1?

I am writing a standard Unix shell in C. How should I handle the error?

2
  • I can't make out what you mean by your last question. Are you talking about shell scripts or the shell itself or where are you going with this?
    – Caleb
    Aug 21, 2011 at 13:51
  • You're right. I edited my question to make it clearer.
    – rahmu
    Aug 21, 2011 at 14:06

3 Answers 3

8

In the C API, system calls return a negative value to indicate an error, and the error code in errno gives more information on the nature of the error. Your man page should explain the possible errors on your system. There are two standard error codes:

  • EAGAIN indicates that the new process cannot be created due to a lack of available resources, either insufficient memory of some kind or a limit that has been reached such as the maximum number of processes per user or overall.
  • ENOMEM indicates that the new process cannot be created due to a lack of memory of some kind. Under Linux, ENOMEM indicates a lack of kernel memory, while a lack of userland memory is reported as EAGAIN. Under OpenBSD, ENOMEM is used for a lack of userland memory as well.

In summary, fork can fail due to a lack of available resources (possibly in the form of an artificial limit rather than a simple lack of memory).

The behavior of shells when fork fails is not specified by POSIX. In practice, they tend to return different error statuses (1 in pdksh, 2 in ash, 254 in bash, 258 in ksh93, 1 in tcsh; zsh returns 0 which is a bug). If you're implementing a shell for production use (as opposed to a learning exercise), it might be worth discussing this on the Austin Group mailing list.

3

I know that the kernel has a parameter NPROC which tells it the maximum amount of processes which can be run at the same time. I imagine if you're already at the maximum and try creating another one, you will be denied from the kernel and return -1 to your parent.

On another note, the kernel also has a limit of processes per user stored in the MAXUPRC parameter. Same deal applies as above.

1

One possible reason would be the inability to spawn a new process due to quota limitations or some system failure.

When writing software you may not always know why something might fail, but having a clearly defined way to handle every step if it doesn't go right is always a good idea.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .