Jaguar vs. Linux: Same code, different output!?


Hi, all,

This questions is for programmers....

On one of the classes I'm taking, we're using ssh to the Linux (RedHat) servers. And the part of the assignments is to create apps on Linux.

I was first very excited because I thought I could take a full use of Unix part of OS X, but apperently, I'm discovering a lot of differences.

My assignment this time, is like this:
type ./prog3 X ...where prog3 is the app name, and X is variable.

This creates X number of child processes, and creates X number of files containing the summation of child ID. For example, if X=5, you'll see 5 files created; Child_1.txt with 1 written in it, Child_2.txt with 3 written in it (1+2), Child_3.txt with 6 written in it (1+2+3), Child_4.txt with 10 written in it (1+2+3+4), and Child_5.txt with 15 written in it (1+2+3+4+5). As files are being created, it displays what's in those files (when you're on the child process, if I'm not mistaken).

This C++ code works just fine when compiled and run on the Linux server, but not on the mac. I first noticed the fact Linux requires 5 more header files and they're not needed on mac (no difference and it compiles just fine without them and produces the same result).

I'm completely puzzled. Can somebody help me solve this?

I attached the source code so you can play with it. (This board doesn't allow me to post .cpp file, so the file extension is changed to .txt. Please change back to .cpp when you use this.)

Any input is greatly appreciated.



Your problem doesn't have anything to do with platform differences. It is just a race condition.

Your program relies on the fact that the child process reads the file after the parent process has finished writing it. This, however, is not guarantteed at all.
Also, you cannot rely on wait(NULL) for this purpose. If you want to guarantee it you must synchronize the processes or explicitely lock the file while writing or reading it.


1) Your temp array is too small. The "Child_%d.txt" format string will result in 11 characters for single digit file numbers. However, a C string requires an invisible 0 terminating byte at the end so your string will be 12 characters.

It is good practice to make arrays big enough for the largest possible value. A 32bit integer can use up to 10 digits so I would suggest to make the temp array at least 22 bytes.

2) strcpy(filename, temp) is not necessary. Why not eliminate the temp array, make filename 22 bytes and sprintf into filename? Anyway, sprintf returns the resulting string length which you assign to xxx. However, you never use this value afterwards, so why the assignment?