- 论坛徽章:
- 0
|
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 |
|