作者在 2010-09-09 11:38:49 发布以下内容
#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) //父进程结束,子进程的父进程id变成1
printf("%d\n",getppid());
}
return 0;
}
#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) //父进程结束,子进程的父进程id变成1
printf("%d\n",getppid());
}
return 0;
}