Is the fork on mac (OSX-10.9.2) with the default c

2019-09-01 03:11发布

问题:

I'm executing this program

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main() {

    pid_t pid;
    pid = getpid();
    printf("my pid is %d", pid);
    fork();
    pid = getpid();
    if(pid < 0) {
            printf("error creating child process");
            exit(1);
    }
    if(pid > 0) {
            printf("\n my child's pid is %d \n", pid);
            exit(0);
    }
    printf("hello from child process, im still running");
    return 0;

}

I expect the result to be :

my pid is 5830
 my child's pid is 5831
hello from child process, i'm still running

But I get these results :

my pid is 5830
 my child's pid is 5830 
my pid is 5830
 my child's pid is 5831 

What am i doing wrong? Well, as the title suggests, i'm running this on my mac - 10.9.2 and

    gcc --version returns :    

    i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM  build 2336.11.00)
    Copyright (C) 2007 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  
    There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

回答1:

Your first printf call has no newline at the end of the string. The write is getting buffered and when the fork occurs you end up with two processes that each have a copy of the buffer. When the parent and child next call printf and include a newline, the buffers get flushed - hence the duplication. Add a newline to the end of the string to fix the duplication.

You also need to be inspecting the return value of fork (not getpid) to determine whether you're in the parent or child. getpid in the child will return the actual pid, not 0. Currently both the parent and the child think they're the parent.



标签: c unix printf fork