简体   繁体   中英

Erlang: Store PID in ETS

In a server I am trying to store it's connected clients and their PIDs in an ets-table.

The table is created as the server is initiated

initate_server() ->
                ets:new(users, [set, named_table]).

When a user is connected to the server I'm calling a function

add_user(PID, Nick) ->
         ets:insert_new(users, {Nick, PID}).

This in turn generates an error saying I'm using a bad argument above. Is it possible to store a PID in an ets-table like this?

The error says the following:

 Something went very wrong! 
    {{case_clause,   
      {'EXIT',    
       {badarg,
        [{ets,insert,[users,{"user01", <0.66.0>}],[]},
          {server, loop, 2,
           [{file,

        filenames and such...

Yes, you can store pids in ETS tables. The reason for the badarg error is probably access control.

By default, ETS tables are created with protected access. That means that any process can read values from the table, but only the process that created the table can write values to it. Depending on how you want it to work, you could either have the client process send a message to the server to insert new values, or create the table with the public option, which lets any process write to the table.

Are you sure that your ets table still exists when you execute the ets:insert_new/2?

An ets table disappears as soon as the process which has created it dies. If you create it in the shell (or a function called by the shell) it will disappear as soon as you type something wrong generating an errors (a simple 2 / 0. will do it). If you created the ets in a function spawned by the shell, it will disappear as soon as this function ends or dies. there is an interesting paper about ets by Steve Vinoski here: Don't Lose Your ets Tables and an implementation by DeadZen here etsgive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM