gpt4 book ai didi

C - 顶级进程和底层(叶)进程之间的命名管道

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:57 28 4
gpt4 key购买 nike

我正在尝试从底层叶进程写入命名管道并从顶层进程的管道读取。

为此,我首先在顶级进程中创建 FIFO,然后使用 for 循环派生更多进程。在 for 循环中,我正在检查叶子进程,如果它是叶子,我正在写入 FIFO 并从循环中中断。然后,在循环之后,我试图从顶层进程中的 FIFO 中读取。这不起作用,我的程序在创建叶进程后卡住并停止。

如何通过 FIFO 将消息从叶节点发送回顶级父进程?

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>

#define MAX_BUF 1024

int main(int argc, char **argv){

int numprocs = atoi(argv[1]);
int lev = numprocs;
fprintf(stdout,"ALIVE: Level %d process with pid=%d, child of ppid=%d.\n", lev, getpid(), getppid());

//create shared memory
const int SIZE = numprocs * sizeof(int);
const char *name = "dleggio1OS";
int shm_fd;
int *ptr;
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
*ptr = getpid();

//create fifo
int fd;
char *myfifo = "/tmp/dleggio1fifo";
mkfifo(myfifo, 0666);

//spawn procs
int i;
for(i = 1; i < numprocs; i++){
lev--;
int pfds[2];
char buf[30];
if(pipe(pfds) == -1){
perror("pipe");
exit(1);
}
pid_t pid;


if((pid = fork()) < 0){
perror("fork");
exit(1);
}

if(pid == 0){ //child

const int SIZE = numprocs * sizeof(int);
const char *name = "dleggio1OS";
int shm_fd;
int *ptr;
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
ptr[i] = getpid();

close(pfds[1]);
if(read(pfds[0], buf, 3) <= 0){
perror("child");
exit(1);
}
int check = atoi(buf);
fprintf(stdout,"ALIVE: Level %d process with pid=%d, child of ppid=%d.\n", check, getpid(), getppid());

if(check == 1){ //leaf
fd = open(myfifo, O_WRONLY);
write(fd,"leaf",sizeof("leaf"));
close(fd);
break;
}

}
else{ //parent
close(pfds[0]);
char hold[3];
sprintf(hold,"%d",lev);
if(write(pfds[1], hold, 3) <= 0){
perror("parent");
exit(1);
}

wait(NULL);
return 0;
}
}

//read fifo
char buff[MAX_BUF];
fd = open(myfifo,O_RDONLY);
read(fd,buff,MAX_BUF);
close(fd);

shm_unlink(name);
unlink(myfifo);
return 0;
}

输出:

ALIVE: Level 3 process with pid=554, child of ppid=451.
ALIVE: Level 2 process with pid=555, child of ppid=554.
ALIVE: Level 1 process with pid=556, child of ppid=555.
_ // <---- stalls here

最佳答案

所有进程都卡在“wait()”调用上(即等待它的一个子进程退出),除了最后一个 fork 的子进程...卡在“open(myfifo, O_WRONLY)”上。 ..最后一个 child 将继续挂起,直到一个进程打开 fifo 进行读取...

关于C - 顶级进程和底层(叶)进程之间的命名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35705514/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com