My code produces weird output in Terminal
I've put a small program to solve the "dining philosophers problem" on repl.it, where it runs as expected and produces the following output:
When I compile and run the same program on macOS I get
I suspect some Terminal settings are wrong here, how can I fix this?
This problem is definitely not due to resetting the NVRAM, so don't worry about that.
You're essentially taking a program (main.c) and compiling it on your Mac with the Apple supplied clang compiler to create the main
executable. This is where you get the deprecation warnings, which in themselves usually do not indicate a problem as such with the program - just that if this were a "real" program (and not an educational demo) you would want to use an alternative for sem_init()
.
The output from this program now differs quite a lot from the output of the same program run on Ubuntu or on repl.it, which is essentially just a kind of remote interface to a Ubuntu machine.
I can confirm that I get the same output as you on the Mac, and that it differs quite a lot from the output on Ubuntu, as it does not adhere to the 11 element width of the outputted table. So this problem is not specific to your Mac.
The reason the program differs is that the implementation of the semaphore functions on macOS differs from the Ubuntu implementation. Normally this would indicate that there's a bug in your main.c program.
The bug is that the code does not check the return value of the sem_init() function in the main() function. If you did check the return value, you would see that it returns -1, which means that an error occured. It is pointless continuing after the error occurs, as this means that essentially every following operation on that semaphore will fail.
The reason the code fails is that you're trying to create an unnamed semaphore, which is not supported on macOS. You could fix the program on macOS by replacing the calls to sem_init()
with calls to sem_open()
. Note that the latter returns a pointer to the semaphore instead of having it as an output parameter.