Working with the Process.spawn function

What could possibly be wrong with respect to this code :

defmodule Test do
  def main do
  Process.spawn(self(), Test.test())
  end
  def test do
     IO.puts("Test ok");
  end
end

Error message :

Test ok
** (ArgumentError) argument error
    erlang.erl:2876: :erlang.spawn_opt(#PID<0.102.0>, :ok)

Proces.spawn/2 takes a function of arity 1 as its first argument, though you pass a pid, also the second argument should be of type Process.spawn_opts/0, which is a list of Process.spawn_opt/0, though you pass the atom :ok.

What do you actually want to do?

I want to spawn a process from another function that outputs a specific text.

Then pass that function as first argument to Kernel.spawn/1, you rarely need to actually use the Process.spawn/* functions.

There is still the same error this time : erlang.spawn(:ok)

Then you are not passing a function, as :ok is an atom.

Can you share your code?

defmodule Test do
  def main do
    spawn(Test.test())
  end

  def test do
     IO.puts("Test ok")
  end
end

You are calling Test.test/0 which prints Test ok and then returns :ok, this return value of Test.test/0 is then passed to spawn/1.

You probably want spawn(&test/0) to pass a “function capture” to spawn/1.

3 Likes

Thanks a lot.

1 Like