C-相同子IDfork和fifo的多个实例

问题描述

我正在尝试实现一个分叉多次的程序。产生的子进程应将其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;
}

这是接收程序:

int main() 
{ 
    int fd; 
    int fd2;
    int fd5;
    int test;
    char *myfifo = "/home/test1";
   test =  mkfifo(myfifo,0600);
    if(test==-1) {
        printf("No such instance exists,terminating...\n");
        exit(1);
       }
    else {
        for(int x=1; x <=7; x++) {
                 int contid;
                  fd5 = open(myfifo,O_RDONLY); 
                  read(fd5,&contid,sizeof(int));   
                  printf("Contestant with ID %d has joined!\n",contid);
                  kill(contid,SIGKILL);
                  printf("Goodbye ID %d\n",contid);                    
                  close(fd5);
        }
    }

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 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.

为什么子进程甚至在据说被杀死后仍会“重新加入”?这个问题的根源是什么?您的帮助将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)