我正在执行这个程序
#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;
}
我期望的结果是:
my pid is 5830 my child's pid is 5831 hello from child process, i'm still running
但是我得到这些结果:
my pid is 5830 my child's pid is 5830 my pid is 5830 my child's pid is 5831
我究竟做错了什么? 那么,正如标题所示,我正在运行在我的Mac – 10.9.2和
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.
你的第一个printf
调用在字符串的末尾没有换行符。 写入被缓冲,当fork
发生时,你最终得到两个进程,每个进程都有一个缓冲区副本。 当下一个父母和孩子调用printf
并包含一个换行符时,缓冲区会被刷新 – 因此是重复的。 在字符串的末尾添加一个换行符以修复重复。
您还需要检查fork
的返回值(而不是getpid
)以确定您是在父级还是子级。 在孩子getpid
将返回实际的PID,而不是0.目前,父母和孩子都认为他们是父母。