c – fork()代码

前端之家收集整理的这篇文章主要介绍了c – fork()代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
void main ()
{
   if ( fork () )
   {
       printf ( "PID1 %d\n",getpid () );
   }
   else
   {
       printf ( "PID2 %d\n",getpid () );
   }
}

这段代码有什么作用?我知道它与进程ID有关但是不应该将某些东西返回到条件中以确定它是否是子进程/父进程?

解决方法

通常它是:
pid_t pid = fork();
if(pid == 0) {
  //child
} else if(pid > 0) {
  //parent
} else {
 //error
}

手册页说:

RETURN VALUE
   Upon successful completion,fork() shall return 0 to the child 
   process and shall return the process ID of the child process to the 
   parent process.  Both processes shall continue to execute from 
   the fork() function. 
   Otherwise,-1 shall be returned to the parent process,no child process 
   shall be created,and errno shall be set to indicate the error.

猜你在找的C&C++相关文章