【发布时间】:2013-09-19 22:24:09
【问题描述】:
鉴于以下代码,我正在尝试解决这个问题:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
char mynum='0';
int main(void)
{
int i;
pid_t fork_return;
static char buffer[10];
fork_return = fork();
if (fork_return == 0)
{
strcpy(buffer, "CHILD"); /*in the child process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
mynum=i + '0';
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
else
{
strcpy(buffer, "PARENT"); /*in the parent process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
}
注意mynum 是一个全局变量。
- 孩子正在递增
mynum的 ASCII 值 - 父母不是
- 孩子和家长可以轮流跑步
为什么子打印CHILD0、CHILD1、CHILD2等,而父打印PARENT0、PARENT0、PARENT0等?记住mynum 是一个全局变量。
另外,如果我fork一个进程,为什么我打印他们的pid,他们的ppid总是一样的?
【问题讨论】: