Chinaunix首页 | 论坛 | 博客
  • 博客访问: 142764
  • 博文数量: 61
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 590
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-03 15:26
文章分类

全部博文(61)

文章存档

2010年(9)

2009年(52)

我的朋友

分类: LINUX

2009-07-16 21:53:19

Process ID
getpid()
我们认为进程ID是不同的,从而作为识别,但是书中讲了一种特列:当一个进程结束时,系统是可以将其进程ID作为候选继续给新的进程的,因此会有可能导致新进程由于使用旧进程ID而错误的被调用
 
进程0是调度进程
进程1是init进程。进程1是普通的用户进程(相对系统进程来说)
 
fork创建新进程
exec执行行程序
exit控制终止
wait和waitpid处理等待终止
 
 
Race Conditions(竞态条件)
 
在下面的代码里,如果不了解很容易犯错。
 

#include "stdio.h"

static void charatatime(char *);

int
main(void)
{
    pid_t pid;

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) {
        charatatime("output from child\n");
    } else {
        charatatime("output from parent\n");
    }
    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);
}

如果执行

$ a . o u t
output from child
output from parent
$ a . o u t
oouuttppuutt ffrroomm cphairlednt
$ a . o u t
oouuttppuutt ffrroomm pcahrielndt
$ a . o u t
ooutput from parent
utput from child

和你想象的不一样吧?因为此时已经是两个进程在执行了,cpu在进程直接的切换导致他们互相影响了~

解决方法:

每个进程在执行完它的一套初始化操作后要通知对方,并且在继续运行之前,要等待另一方完成其初始化操作

#include "stdio.h"

   static void charatatime(char *);

   int
   main(void)
   {
       pid_t pid;

      TELL_WAIT();

       if ((pid = fork()) < 0) {
           err_sys("fork error");
       } else if (pid == 0) {
          WAIT_PARENT(); /* parent goes first */
           charatatime("output from child\n");
       } else {
           charatatime("output from parent\n");
          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);
   }

 
 


作品loseblue创作,采用进行许可。

阅读(654) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~