免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1044 | 回复: 0
打印 上一主题 下一主题

Chapter 8. Process Control--进程控制 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-07-16 21:53 |只看该作者 |倒序浏览
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
创作,采用
知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议
进行许可。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93455/showart_1998625.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP