日期:2014-05-16  浏览次数:20808 次

刚接触linux,结果就让我晕了一把。 fork?!
#include <sys/types.h>
#include <unistd.h>
main()
{
  pid_t pid;
  printf("\nPID before is :%d",getpid());
  pid=fork();
  if(pid<0)
  {
  printf("\nPID NEW IS wrong!");
  }
  else if(pid==0)
  {
  printf("\nI'm child process: %d",getpid());
  }
  else
  {
  printf("\nI'm parent process: %d",getpid());
  } 
}

运行的时候第次的printf输出会输出两次,搞得我真晕菜了。是教材错了么?清华大学出版社出版教材是输出一次。


------解决方案--------------------
”PID before is: “是两次,这里不是因为fork,而是输出的缓冲机制,printf的输出是行缓冲的要接受到换行符或者结束符才有输出。
将每句中的'/n'移到句尾,如"\nPID before is :%d"改为"PID before is :%d\n",你就会得到和书上所说类似的结果了

------解决方案--------------------
楼上说得不错
刚才strace 贴出来可以看到

2337 execve("./e", ["./e"], [/* 25 vars */]) = 0
2337 uname({sys="Linux", node="He", ...}) = 0
2337 brk(0) = 0x804a000
2337 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
2337 open("/etc/ld.so.cache", O_RDONLY) = 3
2337 fstat64(3, {st_mode=S_IFREG|0644, st_size=29618, ...}) = 0
2337 mmap2(NULL, 29618, PROT_READ, MAP_PRIVATE, 3, 0) = 0xb7f8c000
2337 close(3) = 0
2337 open("/lib/libc.so.6", O_RDONLY) = 3
2337 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\310P\1"..., 512) = 512
2337 fstat64(3, {st_mode=S_IFREG|0755, st_size=1195593, ...}) = 0
2337 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7f8b000
2337 mmap2(NULL, 957500, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xb7ea1000
2337 mmap2(0xb7f85000, 16384, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe3) = 0xb7f85000
2337 mmap2(0xb7f89000, 7228, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7f89000
2337 close(3) = 0
2337 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7ea0000
2337 mprotect(0xb7f85000, 8192, PROT_READ) = 0
2337 mprotect(0xb7fa5000, 4096, PROT_READ) = 0
2337 set_thread_area({entry_number:-1 -> 6, base_addr:0xb7ea06b0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0
2337 munmap(0xb7f8c000, 29618) = 0
2337 getpid() = 2337
2337 fstat64(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(4, 2), ...}) = 0
2337 ioctl(1, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 opost isig icanon echo ...}) = 0
2337 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7f93000
2337 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7ea06f8) = 2338
2337 write(1, "PID before is :2337\n", 20) = 20
2337 write(1, "I \'m parent process: 2337\n", 26) = 26
2337 munmap(0xb7f93000, 4096) = 0
2337 exit_group(0) = ?
2338 write(1, "PID before is :2337\n", 20) = 20
2338 write(1, "I \'m child process: 2338\n", 25) = 25
2338 munmap(0xb7f93000, 4096) = 0
2338 exit_group(0) = ?