Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created July 18, 2021 08:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postmodern/a98e68dff96163b5f234cd9de1c5c75d to your computer and use it in GitHub Desktop.
Save postmodern/a98e68dff96163b5f234cd9de1c5c75d to your computer and use it in GitHub Desktop.
Example of adding fork back to Crystal
lib LibC
fun fork : PidT
fun wait(Int *) : PidT
fun waitpid(PidT, Int *, Int) : PidT
end
puts "Before fork"
pid = LibC.fork
if pid == 0
puts "Inside child"
puts "Sleeping in child ..."
sleep 4
puts "Exiting child"
exit 1
else
puts "Inside parent"
status = uninitialized LibC::Int
puts "Waiting for child to exit ..."
LibC.waitpid(pid,pointerof(status),0)
puts "Child exited with #{status}"
end
@postmodern
Copy link
Author

Expected output:

Before fork
Inside parent
Waiting for child to exit ...
Inside child
Sleeping in child ...
Exiting child
Child exited with 256

@postmodern
Copy link
Author

Hmm appears there is a Process.fork, but is :nodoc:ed.
https://github.com/crystal-lang/crystal/blob/1.0.0/src/process.cr#L62-L98

@didactic-drunk
Copy link

Is there a solution for

spawn do
  mutex.synchronize {  }
end

fork do
  # * Fibers are no longer running
  # mutex is stuck in a locked state
end

with -Dpreview_mt?

@postmodern
Copy link
Author

Not sure, but I suspect Fiber/mutex issue happens with Crystal's Process.fork? After the process forks, both the parent and child processes should keep running the fibers and unlock any mutexes?

Building with -Dpreview_mt seems to work with LibC.fork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment