#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
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 child!/n";
n=6;
printf("%d/n",getppid());
}
else
{
message="This is the parent!/n";
n=3;
}
for(;n>0;n--)
{
printf(message);
sleep(1);
if(pid==0) //当父进程结束后子进程的父进程变成init
printf("%d/n",getppid());
}
return 0;
}
子父进程
本文提供了一个使用C语言实现的简单父子进程示例程序。通过fork()系统调用创建子进程,并展示了父子进程间的PID关系及运行情况。父进程与子进程分别输出特定消息,并通过循环与sleep函数模拟简单的并发行为。


被折叠的 条评论
为什么被折叠?



