分类: LINUX
2009-08-06 19:48:10
#include <unistd.h>; 

#include <sys/types.h>; 

main () 



{ 

pid_t pid; 

pid=fork(); 

if (pid < 0) 

printf("error in fork!"); 

else if (pid == 0) 

printf("i am the child process, my process id is %dn",getpid()); 

else 

printf("i am the parent process, my process id is %dn",getpid()); 


} 
#include <unistd.h>
#include <sys/types.h>
main()

{
pid_t pid;
printf("\n[%d]not fork pid=%d\n",getpid(),pid);
pid=fork();
printf("\n[%d]forked pid=%d\n",getpid(),pid);
if(pid<0)
{
printf("error in fork!\n");
getchar();
exit(1);
}
else if(pid==0)
printf("\n[%d]in child process,p_id=%d\n",getpid(),getpid());
else
{
printf("\n[%d]in parent process,my pid=%d\n",getpid(),pid);
printf("\n[%d]in parent process,my getpid=%d\n",getpid(),getpid());
}
}
程序运行结果如下:
[hardy@localhost fork]$ ./fork
[3819]not fork
[3820]forked pid=0
[3820]in child process,p_id=3820
[3819]forked pid=3820
[3819]in parent process,my pid=3820
[3819]in parent process,my getpid=3819
可以清楚的看到 not fork只打印了一次,其中[3819]是父进程的进程号,创建fork以后,fork函数返回给父进程的值pid是子进程的进程号[3820],而在子进程中,pid值为零。也就是说子进程中,pid被置零。
#include <sys/types.h>
#include <unistd.h>
int main()

{
int i;
for( i= 0; i< 3; i++)
{
int pid= fork();
if(pid== 0)
{
printf("son\n");
}
else
{
printf("father\n");
}
}
return 0;
}