[英]How to differentiate child processes?
說我叉N個孩子。 我想創建1到2,2和3,4和5之間的管道,......等等。 所以我需要一些方法來確定哪個孩子是哪個。 下面的代碼是我現在擁有的。 我只需要一些方法告訴孩子號碼n,是孩子號碼n。
int fd[5][2];
int i;
for(i=0; i<5; i++)
{
pipe(fd[i]);
}
int pid = fork();
if(pid == 0)
{
}
下面的代碼將為每個子節點創建一個管道,根據需要多次分叉該進程,並從父節點向每個子節點發送一個int值(我們想要給孩子的id),最后孩子們將讀取價值並終止。
注意:由於您正在分叉,i變量將包含迭代編號,如果迭代編號是子ID,則您不需要使用管道。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int count = 3;
int fd[count][2];
int pid[count];
// create pipe descriptors
for (int i = 0; i < count; i++) {
pipe(fd[i]);
// fork() returns 0 for child process, child-pid for parent process.
pid[i] = fork();
if (pid[i] != 0) {
// parent: writing only, so close read-descriptor.
close(fd[i][0]);
// send the childID on the write-descriptor.
write(fd[i][1], &i, sizeof(i));
printf("Parent(%d) send childID: %d\n", getpid(), i);
// close the write descriptor
close(fd[i][1]);
} else {
// child: reading only, so close the write-descriptor
close(fd[i][1]);
// now read the data (will block)
int id;
read(fd[i][0], &id, sizeof(id));
// in case the id is just the iterator value, we can use that instead of reading data from the pipe
printf("%d Child(%d) received childID: %d\n", i, getpid(), id);
// close the read-descriptor
close(fd[i][0]);
//TODO cleanup fd that are not needed
break;
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.