gen_server documentation

Gunilla Arendt gunilla@REDACTED
Mon Apr 10 08:38:43 CEST 2006

Samuel Rivas wrote:
> Matthias Lang wrote:
>> The documentation is correct.
>> You have overlooked how linked processes must behave. If you link a
>> process and then exit, then your process (the shell, in your example)
>> will exit too.
>> If you don't want that to happen, you can either not link in the first
>> place, or you can trap exits. Example:
>> 3> process_flag(trap_exit, true).
>> false
>> 4> gen_server:start_link(dumb_server, [], []).
>> {error,foo}
>> Matthias
> Mmm yes. I was somehow deceived into believing that gen_server was supposed
> to catch init exits and return {error, Reason}.

The gen_server process *does* catch that the init/1 function exits. It
reports this back to its starter and then terminates with exit reason
= Reason.

The start function, start/3 as well start_link/3, in this case *does*
return {error, Reason}.

> Obviously, you can't catch an spawn_link. My fault.

Well, you can, but there's no point in doing so. 'catch' catches an
error *within* the context of a process. That is,
'catch spawn_link(...)' would only catch an exception raised within
the spawn_link function itself (which won't happen), not an error within
the new process created as a result of calling spawn_link.

> PS: I didn't say the documentation was wrong. I said that those
> functions behave differently, so I was right (just by chance) :)

The functions behave exactly the same, except for that
gen_server:start_link/3 creates a link between the calling process
and the gen_server process.

As Matthias explained, you overlooked how linked processes behave.
You have two processes here: the shell process and the gen_server
process. In both cases, the gen_server process terminates with reason
'foo' and the start function returns {error, foo}.

When you use gen_server:start_link/3, however, the shell process is
linked to the gen_server. When the gen_server terminates, so does
the shell process, before it has had the time to print out the return
value {error, foo}.

Regards, Gunilla

More information about the erlang-questions mailing list