Is the fork on mac (OSX-10.9.2) with the default compiler(gcc-4.2) any different from normal fork?

最后都变了- 提交于 2019-12-11 18:57:35

问题


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.



来源:https://stackoverflow.com/questions/23818222/is-the-fork-on-mac-osx-10-9-2-with-the-default-compilergcc-4-2-any-different

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!