2024年4月29日发(作者:)
3. 进程控制
上一页 第 30 章 进程 下一页
3. 进程控制
3.1. fork函数
#include
#include
pid_t fork(void);
fork调用失败则返回-1,调用成功的返回值见下面的解释。我们通过一
个例子来理解fork是怎样创建新进程的。
例 30.3. fork
#include
#include
#include
#include
int main(void)
{
pid_t pid;
char *message;
int n;
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
}
if (pid == 0) {
message = "This is the childn";
n = 6;
} else {
message = "This is the parentn";
n = 3;
}
for(; n > 0; n--) {
printf(message);
sleep(1);
}
return 0;
}
$ ./
This is the child
This is the parent
This is the child
This is the parent
This is the child
This is the parent
This is the child
$ This is the child
This is the child
发布评论