一个疏忽导致的问题

来源:互联网 发布:永邦软件科技有限公司 编辑:程序博客网 时间:2024/05/09 12:25

最近在看 Unix 环境高级编程 这本书,书上列举了一个进程 racing 的例子,由于打印字符串太短,所以看不到整体的效果,于是自己写了一个测试程序,大家看看这个程序输出的结果是什么?

#include "apue.h"

static void charatatime(char *);

char buf_1[4096];
char buf_2[4096];

int
main(void)
{
 pid_t pid;
 memset(buf_1, '1', 4096);
 memset(buf_2, '2', 4096);
 TELL_WAIT();

 if ((pid = fork()) < 0) {
  err_sys("fork error");
 } else if (pid == 0) {
  WAIT_PARENT();  /* parent goes first */
  charatatime(buf_1);
 } else {
  charatatime(buf_2);
  TELL_CHILD(pid);
 }
 exit(0);
}

static void
charatatime(char *str)
{
 char *ptr;
 int  c;

 setbuf(stdout, NULL);   /* set unbuffered */
 for (ptr = str; (c = *ptr++) != 0; )
  putc(c, stdout);
}

原创粉丝点击