if(fork()==0)
{
....
if(fork()==0)
{}
}
else
{
//父进程获取子进程的pid
//我是想这样写
pid_t pid1=wait(0);//这是获取第一个子进程pid
pid_t pid2=wait(0);//我本想这是第二个子进程pid,可是结果是-1,我想了下应该第二个子进程是第一个子进程的子进程,所以这样不行
//我的问题就是,父进程怎么样能你获得到第二个子进程的pid呢?
}
那就在把第二次fork安排在父进程里嘛
pid_t pid1, pid2
pid1 = fork();
if (pid1 > 0)
{
pid2 = fork();
} #include<unistd.h>
pid_t f1,s1,s2;
int main()
{
f1=getpid();//父
s1=fork();//子1
s2=fork();//子2
printf("%d\n%d\n%d\n",f1,s1,s2);
return 0;
}
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/shm.h> #include <stdlib.h> int main(void) { int shmid = 0; int *shmbuf = NULL; if((shmid = shmget(777, sizeof(int), 0666 | IPC_CREAT)) < 0) { perror("shmget"); exit(-1); } if((shmbuf = shmat(shmid, NULL, 0)) < 0) { perror("shmat"); exit(-1); } if(0 == fork()) { if(0 == fork()) { printf("I'm the child of child1. my pid = %d, pid_father = %d\n", getpid(), getppid()); *shmbuf = getpid(); } else { printf("I'm child1. my pid = %d, pid_father = %d, pid_my_child = %d\n", getpid(), getppid(), wait(NULL)); } } else { printf("I'm father. my pid = %d, pid_my_child = %d, ", getpid(), wait(NULL)); printf("pid_child_of_child1 = %d\n", *shmbuf); if(shmdt(shmbuf) < 0) { perror("shmdt"); exit(-1); } if(shmctl(shmid, IPC_RMID, NULL) < 0) { perror("shmctl"); exit(-1); } } return 0; }
程序的执行结果:
I'm the child of child1. my pid = 26919, pid_father = 26918
I'm child1. my pid = 26918, pid_father = 26917, pid_my_child = 26919
I'm father. my pid = 26917, pid_my_child = 26918, pid_child_of_child1 = 26919