C-同一子ID的多个实例(fork和fifo)

C-同一子ID的多个实例(fork和fifo),c,fork,child-process,fifo,mkfifo,C,Fork,Child Process,Fifo,Mkfifo,我正在尝试实现一个多次分叉的程序。产生的子进程应该将它们的ID发送给另一个程序,即接收方程序,然后接收方程序应该继续逐个杀死它们 这是主程序: int main() { int fd1; int fd2; int fd3; int fd4; int test; int set; char *myfifo = "/home/test1"; for(int i=0; i <7; i++) {

我正在尝试实现一个多次分叉的程序。产生的子进程应该将它们的ID发送给另一个程序,即接收方程序,然后接收方程序应该继续逐个杀死它们

这是主程序:

int main() 
{ 
    int fd1; 
    int fd2;
    int fd3; 
    int fd4;
    int test;
    int set;
    char *myfifo = "/home/test1";
    for(int i=0; i <7; i++) {
        if(fork()==0) {
                 test = mkfifo(myfifo, 0600);  
                if(((test==0)||(test==-1))&&(errno!=EEXIST)) {
                    printf("No such instance exists, terminating...\n");
                    exit(1);
                   }
                else {
                    set = getpid();
                    fd2 = open(myfifo,O_WRONLY);                        
                    write(fd2, &set,sizeof(int)); 
                    close(fd2); 
                    }
        exit(0);
        }
}

    for(int k=0; k<7; k++)
    wait(NULL);
return 0;
}
但我得到的是:

Contestant with ID 18230 has joined!
Goodbye ID 18230.
Contestant with ID 18229 has joined!
Goodbye ID 18229.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18227 has joined!
Goodbye ID 18227.

为什么即使在被假定为已被杀死后,仍有子进程“重新加入”?这个问题的根源是什么?非常感谢您的帮助。

您应该检查
read
的返回值。最好在开始循环之前创建并打开FIFO。您应该检查每个系统调用时出错,并报告任何故障。您可能应该在这两个进程中使用基于零的循环。您应该在接收器进程中循环读取,直到EOF。如果两个孩子足够快地向FIFO写入数据,接收者会丢弃其中一个数字。尝试了你的两个建议(检查读取返回值/注意EOF),我认为它现在起作用了!我只是不知道到底为什么。。。。
Contestant with ID 18230 has joined!
Goodbye ID 18230.
Contestant with ID 18229 has joined!
Goodbye ID 18229.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18227 has joined!
Goodbye ID 18227.
Contestant with ID 18230 has joined!
Goodbye ID 18230.
Contestant with ID 18229 has joined!
Goodbye ID 18229.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18227 has joined!
Goodbye ID 18227.