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.