用getpid可以判断当前是子进程还是父进程。
看下面这个例子:[code]#include
#include
#include
int main()
{
pid_t pid;
static int n = 0;
printf("fork!\n");
switch (pid = fork())
{
case -1:
{
/* ..pid.-1.fork.... */
/* ........ */
/* .......... */
perror("The fork failed!");
break;
}
case 0:
{
/* pid.0.... */
printf("[child]i am child!\n");
printf("[child]getpid=[%d]\n", getpid() );
printf("[child]pid=[%d]\n", pid );
break;
}
default:
{
/* pid..0.... */
printf("[parent]i am parent!\n" );
printf("[parent]getpid=[%d]\n",getpid() );
printf("[parent]pid=[%d]\n",pid );
break;
}
}
printf("n=[%d]\n", n++);
return 0;
}[/code]这个例子在linux下用gcc编译,运行结果如下:[code]fork!
[child]i am child!
[child]getpid=[7422]
[child]pid=[0]
n=[0]
[parent]i am parent!
[parent]getpid=[7421]
[parent]pid=[7422]
n=[0][/code]