C 如何区分子进程?

C 如何区分子进程?,c,linux,process,fork,C,Linux,Process,Fork,比如说我有个孩子。我想在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) { } intfd[5][2]; int i; 对于(i=0;i以下代码将为每个子级创建一个管道,根据需要多次分叉进程,并从父

比如说我有个孩子。我想在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)
{
}
intfd[5][2];
int i;

对于(i=0;i以下代码将为每个子级创建一个管道,根据需要多次分叉进程,并从父级向每个子级发送一个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;
}
#包括
#包括
#包括
int main(int argc,char*argv[]){
整数计数=3;
int fd[计数][2];
int pid[计数];
//创建管道描述符
for(int i=0;i
Make
pid
一个大小为
N
的数组。