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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...